---

# (DD01) Business Logic — UI.button() [37 LOC]

| Field | Value |
|-------|-------|
| Fully Qualified Name | `com.github.blaxk3.ui.UI` |
| Layer | Utility / UI Component (Package: `com.github.blaxk3.ui`) |
| Module | `ui` (Package: `com.github.blaxk3.ui`) |

## 1. Role

### UI.button()

`UI.button()` is a private factory method that constructs and returns an array of three `JButton` components — **Convert**, **Swap**, and **Clear** — used within the Currency Converter application's graphical interface. It serves as a **UI component builder**, encapsulating button creation, visual sizing, and event registration logic into a single reusable unit.

The method performs three distinct business operations through its registered action listeners: (1) the **Convert** button triggers a real-time currency conversion by fetching live exchange rates from the Exchangerate API, parsing user input, and displaying the converted amount; (2) the **Swap** button exchanges the selected source and target currency codes between the two combo boxes, enabling rapid reversal of conversion direction; (3) the **Clear** button resets the input text field and output label to empty strings, providing a quick user interface reset.

This method implements the **command pattern** via anonymous `ActionListener` classes, where each button click maps to a self-contained block of logic. It is a **shared UI utility** called from `panel()` (via `button()[0]`, `button()[1]`, `button()[2]`) to populate the application's layout panel, and has no callers outside the `UI` class itself.

## 2. Processing Pattern (Detailed Business Logic)

```mermaid
flowchart TD
    START(["button()"])
    CREATE_BUTTONS["Create JButton array: Convert, Swap, Clear"]
    SET_DIMENSIONS["Set Dimension(200, 35) for each button"]
    CREATE_RATE_API["Create CurrencyRateAPI instance"]
    REGISTER_CONVERT["Register Convert button ActionListener"]
    CONVERT_VALIDATE["Validate: textField not empty and not just '.'"]
    CONVERT_PARSE_AND_CONVERT["Parse combo items and amount, call rate.convert()"]
    CONVERT_FORMAT["Format result with DecimalFormat '#,###.###'"]
    CONVERT_SET_LABEL["Call setLabel() with formatted result"]
    CONVERT_SHOW_ERROR["Show JOptionPane error message"]
    CONVERT_CATCH["Catch MalformedURLException | URISyntaxException -> throw RuntimeException"]
    REGISTER_SWAP["Register Swap button ActionListener"]
    SWAP_EXECUTE["Swap combo box selections"]
    REGISTER_CLEAR["Register Clear button ActionListener"]
    CLEAR_RESET["Clear text field and label"]
    RETURN_BUTTONS["Return JButton[]"]

    START --> CREATE_BUTTONS --> SET_DIMENSIONS --> CREATE_RATE_API --> REGISTER_CONVERT --> CONVERT_VALIDATE
    CONVERT_VALIDATE -->|"true"| CONVERT_PARSE_AND_CONVERT --> CONVERT_FORMAT --> CONVERT_SET_LABEL --> END_CONVERT
    CONVERT_VALIDATE -->|"false"| CONVERT_SHOW_ERROR --> END_CONVERT
    CONVERT_PARSE_AND_CONVERT --> CONVERT_CATCH
    CONVERT_FORMAT --> CONVERT_CATCH
    CONVERT_SET_LABEL --> CONVERT_CATCH
    CONVERT_SHOW_ERROR --> CONVERT_CATCH
    END_CONVERT --> REGISTER_SWAP --> SWAP_EXECUTE --> REGISTER_CLEAR --> CLEAR_RESET --> RETURN_BUTTONS
```

**Business meaning of key values:**

| Value | Meaning |
|-------|---------|
| `"Convert"` | Button label — triggers currency conversion via Exchangerate API |
| `"Swap"` | Button label — exchanges source/target currency between combo boxes |
| `"Clear"` | Button label — resets input and output display fields |
| `Dimension(200, 35)` | Uniform button sizing across all three action buttons |
| `"#,###.###"` | DecimalFormat pattern — groups thousands with commas, displays up to 3 decimal places |
| `\".\"` | Validation guard — prevents processing when the text field contains only a decimal point |

## 3. Parameter Analysis

| No | Parameter Name | Type | Business Description |
|----|---------------|------|---------------------|
| - | (none) | - | This method takes no parameters. It operates entirely on instance fields and local state. |

**Instance fields accessed by this method:**

| Field | Type | Business Description |
|-------|------|---------------------|
| `textField` | `JTextField` | The numeric input field where the user enters the amount to convert. Validated for non-empty and non-dot-only content. |
| `label` | `JLabel` | The output display field that shows the formatted conversion result (e.g., "1,234.567") or cleared state. |
| `comboBox1` | `JComboBox<String>` | The source currency selector (e.g., USD, EUR, GBP). Its selected item is parsed and passed to the conversion API. |
| `comboBox2` | `JComboBox<String>` | The target currency selector. Used as the destination currency in conversion and swapped with `comboBox1` on Swap button. |

## 4. CRUD Operations / Called Services

### Pre-computed evidence from code analysis graph:

| CRUD | SC / CBS | SC Code | Entity / DB | Operation Description |
|------|----------|---------|-------------|----------------------|
| - | `CurrencyRateAPI.convert` | CurrencyRateAPI | - | Calls `convert(String, String, BigDecimal)` in `CurrencyRateAPI` to perform real-time currency exchange rate conversion via HTTP GET to Exchangerate API |
| R | `UI.getComboBox1` | UI | - | Calls `getComboBox1` in `UI` to retrieve the source currency combo box for reading the selected item |
| R | `UI.getComboBox1` | UI | - | Calls `getComboBox1` in `UI` again during Swap button logic to read the current target currency (now in comboBox1 after partial swap) |
| R | `UI.getComboBox1` | UI | - | Calls `getComboBox1` in `UI` — third reference (used in Swap action listener: `getComboBox1().setSelectedItem(...)`) |
| R | `UI.getComboBox2` | UI | - | Calls `getComboBox2` in `UI` to retrieve the target currency combo box for reading the selected item |
| R | `UI.getComboBox2` | UI | - | Calls `getComboBox2` in `UI` — second reference during Swap logic |
| R | `UI.getComboBox2` | UI | - | Calls `getComboBox2` in `UI` — third reference (used in Swap action listener) |
| R | `UI.getTextField` | UI | - | Calls `getTextField` in `UI` to retrieve the numeric input field for reading the amount string |
| R | `UI.getTextField` | UI | - | Calls `getTextField` in `UI` — second reference (used in Swap action listener context) |
| - | `UI.setLabel` | UI | - | Calls `setLabel(String)` in `UI` to update the output display label with the formatted conversion result |
| - | `UI.setLabel` | UI | - | Calls `setLabel(String)` in `UI` — second reference during Clear button reset |
| - | `UI.setTextField` | UI | - | Calls `setTextField(String)` in `UI` to clear/reset the input text field during Clear button action |

## 5. Dependency Trace

### Pre-computed evidence from code analysis graph:

No screen/batch entry points found within 8 hops. Direct callers found: 1 methods.
Terminal operations from this method: `convert` [-], `getComboBox1` [R], `getComboBox1` [R], `getComboBox1` [R], `getComboBox2` [R], `getComboBox2` [R], `getComboBox2` [R], `getTextField` [R], `getTextField` [R], `setTextField` [-], `setLabel` [-], `setLabel` [-]

Trace who calls this method and what this method ultimately calls.

| # | Caller (Screen/Batch) | Call Chain (Full Path to this Method) | Terminal (SC / CRUD / Entity) |
|---|----------------------|--------------------------------------|-------------------------------|
| 1 | UI.panel() (private method) | `UI.panel()` -> `button()[0]`, `button()[1]`, `button()[2]` | `CurrencyRateAPI.convert [-] Exchangerate API HTTP (no DB)` |

**Notes:**
- `button()` is a private method with a single caller: `UI.panel()` (line 95-97), which accesses `button()[0]`, `button()[1]`, and `button()[2]` to add the three buttons to `panelFramePanel2`.
- The `UI` class itself is instantiated directly in the main application constructor flow — there is no formal screen/batch entry point in this codebase.
- Terminal operations all resolve to in-memory UI component access or the external `CurrencyRateAPI.convert()` HTTP call, which hits `https://v6.exchangerate-api.com/v6/{API_KEY}/pair/{from}/{to}/{amount}` — no database entities are involved.

## 6. Per-Branch Detail Blocks

### Block 1 — [CREATION] Button Array Construction (L112–118)

> Creates a new `JButton` array with three buttons labeled "Convert", "Swap", and "Clear". Then iterates over each button to set a uniform size of 200x35 pixels.

| # | Type | Code |
|---|------|------|
| 1 | SET | `JButton[] button = new JButton[] { new JButton("Convert"), new JButton("Swap"), new JButton("Clear") }` |
| 2 | SET | `buttons.setPreferredSize(new Dimension(200, 35))` for each button in loop (L117) |

### Block 2 — [IF-ELSE] Convert Button Action Listener (L120–133)

> Registers an `ActionListener` on the "Convert" button. On click, validates user input, calls the external currency conversion API, formats and displays the result. If validation fails, shows an error dialog. Catches network-related exceptions and wraps them in `RuntimeException`.

| # | Type | Code |
|---|------|------|
| 1 | SET | `CurrencyRateAPI rate = new CurrencyRateAPI()` (L120) |
| 2 | EXEC | `button[0].addActionListener(convert -> { ... })` — anonymous ActionListener registered on "Convert" button (L121) |

#### Block 2.1 — [IF] Input Validation (`getText() not empty AND not "."`) (L122–132)

> Checks that the text field contains meaningful input before attempting conversion. The guard against `"."` (a lone decimal point) prevents the API call with a partially-formed or invalid number.

| # | Type | Code |
|---|------|------|
| 1 | SET | `getTextField().getText()` — retrieves input string |
| 2 | SET | `getTextField().getText().equals(".")` — compares against lone decimal point |
| 3 | EXEC | `Double.parseDouble(rate.convert(...))` — parses conversion result as Double |
| 4 | CALL | `rate.convert(fromCurrency, toCurrency, amount)` — calls CurrencyRateAPI.convert with the three arguments |
| 5 | CALL | `getComboBox1().getSelectedItem().toString()` — retrieves source currency code (e.g., "USD") |
| 6 | CALL | `getComboBox2().getSelectedItem().toString()` — retrieves target currency code (e.g., "EUR") |
| 7 | SET | `Double.parseDouble(textField.getText())` — parses the user-entered amount as Double |
| 8 | EXEC | `BigDecimal.valueOf(Double.parseDouble(textField.getText()))` — converts to BigDecimal for API call |
| 9 | SET | `new DecimalFormat("#,###.###").format(result)` — formats the numeric result |
| 10 | EXEC | `setLabel(formattedString)` — writes the formatted conversion result to the output label |

#### Block 2.2 — [ELSE] Input Validation Failure — Error Dialog (L128)

> Displays a modal error dialog instructing the user to enter an amount.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `javax.swing.JOptionPane.showMessageDialog(null, "Please enter the amount you need", "Error", JOptionPane.ERROR_MESSAGE)` (L128) |

#### Block 2.3 — [TRY-CATCH] Exception Handling (L129–132)

> Catches `MalformedURLException` and `URISyntaxException` thrown by `rate.convert()`, wrapping them in a `RuntimeException`.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `throw new RuntimeException(ex)` (L132) — rethrows as runtime exception |

### Block 3 — [ELSE-IF] Swap Button Action Listener (L135–139)

> Registered on the "Swap" button. Reads the currently selected item from `comboBox1` into a temporary `String`, then sets `comboBox1`'s selection to `comboBox2`'s current selection, and sets `comboBox2`'s selection to the saved `boxItem`. This effectively swaps the source and target currencies.

| # | Type | Code |
|---|------|------|
| 1 | SET | `String boxItem = Objects.requireNonNull(getComboBox1().getSelectedItem()).toString()` — reads source currency |
| 2 | EXEC | `getComboBox1().setSelectedItem(getComboBox2().getSelectedItem())` — sets comboBox1 to target currency |
| 3 | EXEC | `getComboBox2().setSelectedItem(boxItem)` — sets comboBox2 to the saved source currency |

### Block 4 — [ELSE-IF] Clear Button Action Listener (L141–145)

> Registered on the "Clear" button. Resets the input text field and output label to empty strings, providing a full UI reset for the user to start a new conversion.

| # | Type | Code |
|---|------|------|
| 1 | EXEC | `setTextField("")` — clears the input text field (L142) |
| 2 | EXEC | `setLabel("")` — clears the output label (L143) |

### Block 5 — [RETURN] Return Button Array (L147)

> Returns the `JButton[]` containing all three configured buttons back to the caller (`UI.panel()`).

| # | Type | Code |
|---|------|------|
| 1 | RETURN | `return button;` — returns the JButton array |

## 7. Glossary

| Term | Type | Business Meaning |
|------|------|------------------|
| `UI` | Class | The main Swing JFrame window class for the Currency Converter application. |
| `button()` | Method | Private factory method that creates and configures the three action buttons (Convert, Swap, Clear). |
| `JButton` | Component | Java Swing button widget — interactive element the user clicks to trigger Convert, Swap, or Clear actions. |
| `Convert` | Business action | Triggers real-time currency exchange rate lookup and conversion using the Exchangerate API. |
| `Swap` | Business action | Exchanges the source and target currency selections between the two combo boxes. |
| `Clear` | Business action | Resets the input amount field and the output result label to empty strings. |
| `textField` | Field | Swing `JTextField` where the user enters the numeric amount to be converted. |
| `label` | Field | Swing `JLabel` that displays the formatted conversion result to the user. |
| `comboBox1` | Field | First currency selector combo box — represents the source currency for conversion. |
| `comboBox2` | Field | Second currency selector combo box — represents the target currency for conversion. |
| `CurrencyRateAPI` | Class | HTTP-based API client that queries the Exchangerate API (v6.exchangerate-api.com) for exchange rates and currency conversion. |
| `CurrencyRateAPI.convert` | Method | External API method — performs a GET request to `{base_url}/pair/{from}/{to}/{amount}` and returns the conversion result string. |
| `DecimalFormat` | Utility | Java `java.text.DecimalFormat` — formats numeric output with thousands separators (`#`) and up to 3 decimal places (`###`). |
| `Exchangerate API` | External service | Third-party REST API providing live currency exchange rates. Base URL: `https://v6.exchangerate-api.com/v6/{API_KEY}`. |
| `pair/{from}/{to}/{amount}` | API endpoint | Exchange rate conversion endpoint — returns the converted amount when given a source currency, target currency, and amount. |
| `ActionListener` | Design pattern | Java Swing event listener interface — each button registers an anonymous implementation to define click behavior. |

---
