# Com / Github / Blaxk3 / Converter

## Overview

This module is the application entry point for a desktop Currency Converter application. It contains a single class, `CurrencyConverter`, whose `main` method bootstraps a Swing-based graphical user interface. The module itself does no conversion logic — it acts purely as an anchor, launching the `UI` component from the `com.github.blaxk3.ui` package which handles the window, inputs, and interaction with the exchange rate API.

## Key Classes

### CurrencyConverter

**Source:** [CurrencyConverter.java](src/main/java/com/github/blaxk3/converter/CurrencyConverter.java)

The `CurrencyConverter` class is the program's entry point. It contains a single `main` method and delegates all responsibility for the application's behavior to the `UI` class.

#### `main(String[] args)`

```java
public static void main(String[] args) {
    SwingUtilities.invokeLater(UI::new);
}
```

- **Purpose:** Bootstraps the application on the Swing event dispatch thread (EDT).
- **Parameters:** `args` — standard Java command-line arguments (unused; the application accepts no runtime configuration).
- **Return value:** `void`.
- **Side effects:** Creates and displays the `UI` window.

The use of `SwingUtilities.invokeLater(...)` ensures the UI is constructed on the EDT, which is a Swing best practice. This prevents race conditions that can occur when UI components are created from the main thread. The method passes `UI::new` as a method reference, so the `UI` constructor runs inside the lambda on the EDT.

## How It Works

The application follows a simple bootstrap flow:

1. **`CurrencyConverter.main`** is called when the application starts (e.g., via `java -jar` or an IDE run configuration).
2. It schedules the **UI constructor** to run on the Swing EDT via `SwingUtilities.invokeLater`.
3. The **UI constructor** builds the entire application window:
   - Sets the window title to "Currency Converter", size to 500x500, and centers it on screen.
   - Creates two panes arranged in a 2-column grid layout.
   - Left pane: an input text field (amount to convert) and a dropdown for the source currency.
   - Right pane: an output label (result), a dropdown for the target currency, and three buttons ("Convert", "Swap", "Clear").
4. Both currency dropdowns are populated asynchronously by a `CurrencyCode` background task, which fetches available currency codes from `CurrencyRateAPI`.
5. When the user enters an amount and clicks "Convert", the UI calls `CurrencyRateAPI.convert(...)` to fetch the exchange rate and compute the result, formatting the output with `DecimalFormat`.

### UI Component Layout

The UI window uses a `GridLayout(1, 2)` with two child panels, each using `BoxLayout` (Y-axis):

- **Top-left panel** (dark gray background):
  - `JTextField` — large, bold font for entering the amount.
  - `JComboBox` — source currency selection.
- **Bottom-right panel** (dark gray background):
  - `JLabel` — displays the conversion result.
  - `JComboBox` — target currency selection.
  - Three `JButton` elements: "Convert", "Swap", "Clear".

### Currency Code Population

Both dropdowns are populated by a nested `CurrencyCode` class (a `SwingWorker`) that:

1. Fetches the list of available currency codes from `CurrencyRateAPI.getCurrencyCode()` in a background thread.
2. On completion (`done()`), sorts the codes alphabetically and populates the associated `JComboBox`.
3. Logs any errors via SLF4J's `Logger`.

This keeps the UI responsive while the network request is in flight.

### Conversion Flow

1. User types a numeric amount into the text field.
2. User selects a source and target currency from the dropdowns.
3. User clicks "Convert".
4. The action listener validates that the text field is non-empty, then calls `CurrencyRateAPI.convert(sourceCurrency, targetCurrency, amount)`.
5. The result is formatted with `DecimalFormat("#,###.###")` and displayed in the label.
6. If the API throws `MalformedURLException` or `URISyntaxException`, the exception is wrapped in a `RuntimeException`.

### Swap and Clear Buttons

- **Swap:** Exchanges the selected source and target currencies between the two dropdowns.
- **Clear:** Clears both the input text field and the result label.

## Data Model

There are no persistent data models in this module. The application uses the following types at runtime:

| Type | Source | Purpose |
|---|---|---|
| `String` | Java stdlib | Currency codes (e.g., "USD", "EUR") |
| `Double` / `BigDecimal` | Java stdlib | Numeric amounts for conversion |
| `String[]` | `CurrencyRateAPI` | Array of available currency code strings |

The input field accepts only numeric characters and a single decimal point, enforced by the `NumericFilter` (a `DocumentFilter` inner class in the `UI` package).

## Dependencies and Integration

### Internal Dependencies

This module declares a single package-level dependency:

- **`com.github.blaxk3.ui.UI`** — The `UI` class that `main()` instantiates. This is the application's GUI and contains all the business interaction logic.

### External Dependencies

The `UI` class (transitively loaded by this module) depends on:

| Dependency | Purpose |
|---|---|
| `javax.swing` (JFrame, JButton, JComboBox, etc.) | Desktop GUI framework |
| `com.github.blaxk3.api.CurrencyRateAPI` | External exchange rate API client — fetches currency codes and performs conversion |
| `org.slf4j` | Logging |
| `java.awt` / `java.math` | GUI layout and decimal arithmetic |

The `CurrencyRateAPI` is the key integration point. It provides two operations:

- `getCurrencyCode()` — returns an array of currency code strings.
- `convert(from, to, amount)` — performs a currency conversion using real-time rates from a remote service.

## Notes for Developers

- **Single responsibility:** This module's only job is to start the application. All UI logic, data fetching, and conversion live in `com.github.blaxk3.ui` and `com.github.blaxk3.api`. Do not add logic to `CurrencyConverter.main` — if something needs bootstrapping, extend the `UI` constructor or a dedicated initializer class.

- **Thread safety:** The UI always runs on the EDT. The `CurrencyCode` worker fetches currency codes off the EDT, so UI updates happen in `done()` which runs back on the EDT. Any new background work should follow the same `SwingWorker` pattern.

- **No input validation beyond numerics:** The `NumericFilter` prevents non-numeric input, but does not validate amount ranges or handle edge cases like leading zeros differently. The "Convert" button checks only for an empty field.

- **Error handling:** API errors during conversion throw a `RuntimeException` wrapping the original exception. This is a quick termination strategy — consider replacing it with user-friendly error dialogs in `UI` for a better experience.

- **SwingUtilities.invokeLater:** Always use this pattern when launching Swing apps. Creating the `UI` directly (without `invokeLater`) would bypass this and could cause thread-safety issues.

## Architecture Diagram

```mermaid
flowchart TD
    A["CurrencyConverter"] -->|"launches on EDT via invokeLater"| B["UI JFrame"]
    B -->|"uses"| C["CurrencyRateAPI"]
    B -->|"uses"| D["NumericFilter"]
    B -->|"uses"| E["CurrencyCode SwingWorker"]
    C -->|"calls remote service"| F["External Exchange Rate API"]
```

**Diagram legend:**

- **CurrencyConverter** — Entry point. Creates the UI on the EDT.
- **UI** — The main application window, containing all interactive components.
- **CurrencyRateAPI** — API client that fetches currency codes and performs conversions.
- **NumericFilter** — Input validation ensuring only numeric values are accepted.
- **CurrencyCode** — Background worker that populates currency dropdowns.
- **External Exchange Rate API** — Remote service providing live exchange rates.
