Explore a comprehensive guide on building a Java Swing-based currency converter project. Learn how to create a user-friendly GUI, implement real-time currency conversion, and handle errors effectively with Java. Perfect for developers looking to enhance their desktop application skills.
Currency Conversion Logic
The currency conversion logic is the backbone of this application. Here’s a step-by-step breakdown:
- Base Currency: The base currency is set to USD (United States Dollar). All conversions are calculated relative to this base.
- Exchange Rates: Exchange rates are predefined in a
HashMap
. This map stores currency codes as keys (e.g., “EUR”, “GBP”, “CHF”) and their respective conversion rates as values. - Conversion Method (
convertCurrency
): This method handles the actual conversion:- From USD to Another Currency: If the source currency is USD, the amount is multiplied by the exchange rate of the target currency.
- From Another Currency to USD: If the target currency is USD, the amount is divided by the exchange rate of the source currency.
- Between Two Non-USD Currencies: If neither currency is USD, the method first converts the amount to USD, then to the target currency.
Error Handling: The method throws an IllegalArgumentException
if an unsupported currency is provided or if a conversion isn’t possible with the available data.
NOTE
- The code of currency converter is available in the GitHub repository
- Download the Zip file of currency converter in java
User Interface Design
- Main Frame: The main window of the application is created using
JFrame
. It’s sized at 600×350 pixels, providing ample space for the components. The background color and layout are set to give a modern look. - GridBagLayout: This layout manager is used to position components in a flexible grid. It allows precise control over component alignment and spacing, making it ideal for this type of form-based application.
- Components:
- Labels (
JLabel
): Used to describe the purpose of each input field (e.g., “Amount:”, “From Currency:”, “To Currency:”). They are styled with white text on a dark background for contrast. - Text Field (
JTextField
): Where users enter the amount to convert. It’s styled with a border and tooltip for a better user experience. - Combo Boxes (
JComboBox
): Allow users to select currencies from a list. They are styled with borders and use the same font for consistency. - Button (
JButton
): Triggers the conversion process. It is styled with a background color that matches the application’s theme.
- Labels (
Currency Conversion Logic
- Real-Time Updates: As users type or change currency selections, the application updates the conversion result immediately. This is achieved by attaching a
KeyAdapter
to the text field and action listeners to the combo boxes. - Error Handling: If the user enters invalid data or selects unsupported currencies, the application displays appropriate error messages.
GUI Components and Layout
Main Frame:
JFrame
: This is the top-level container for the application window. It holds all other components.- Size and Close Operation: The frame is set to 600×350 pixels and configured to exit the application when the window is closed.
Layout Management:
GridBagLayout
: A flexible layout manager that allows you to specify constraints for each component. It’s ideal for complex layouts where components need precise positioning and alignment.GridBagConstraints
: This class is used to set constraints for the components. It includes properties likegridx
,gridy
(position),insets
(padding), andgridwidth
(how many columns a component should span).
Components:
- Labels (
JLabel
): Used to describe the purpose of input fields and dropdown menus.- Styling: Labels are styled with white text and bold fonts to stand out against the dark background.
- Text Field (
JTextField
): Allows users to input the amount they want to convert.- Border: A border is added for better visibility and interaction.
- Tooltip: Provides a hint to the user on what to enter.
- Combo Boxes (
JComboBox
): Dropdown menus for selecting currencies.- Font and Border: Consistent with the text field for a cohesive look.
- Button (
JButton
): A button to trigger the conversion.- Styling: Background color and font are chosen to match the application’s theme, and the button is designed to be visually appealing.
Real-Time Conversion
Key Adapter:
KeyAdapter
: This class listens for key events on the text field. When the user types in the text field, thekeyReleased
method is called to update the conversion result.- Error Handling: The
keyReleased
method includes exception handling to catchNumberFormatException
if the input is not a valid number andIllegalArgumentException
if there are issues with currency conversion.
- Error Handling: The
Action Listeners:
- Combo Box Actions: Listeners are added to the currency combo boxes to trigger the conversion when the selected item changes. This ensures the result updates dynamically when users change currency selections.
3. Error Handling:
- Invalid Inputs: The application catches
NumberFormatException
if the user inputs non-numeric values and displays a message prompting for a valid number. - Unsupported Currencies: If the conversion cannot be performed due to missing exchange rates, an
IllegalArgumentException
is thrown, and an error message is shown.
Conclusion
This Java Swing currency converter project showcases the use of Swing components to build a functional and visually appealing desktop application. By leveraging Java’s GUI capabilities, you can create applications that are not only useful but also provide a pleasant user experience.
The application’s use of GridBagLayout ensures a flexible and adaptable UI, while the design choices enhance readability and usability. Real-time updates and comprehensive error handling make it robust and user-friendly. This example serves as an excellent starting point for anyone looking to develop their own Java-based desktop applications or enhance their understanding of Java Swing’s capabilities.
Source Code of Currency Converter project
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
class CoolCurrencyConverterGUI {
// Currency data provided
private static final String BASE_CURRENCY = "USD";
private static final Map<String, Double> exchangeRates = new HashMap<>();
static {
exchangeRates.put("EUR", 0.90702);
exchangeRates.put("GBP", 0.77862);
exchangeRates.put("CHF", 0.86297);
}
public static double convertCurrency(double amount, String fromCurrency, String toCurrency) {
if (fromCurrency.equals(BASE_CURRENCY)) {
if (exchangeRates.containsKey(toCurrency)) {
return amount * exchangeRates.get(toCurrency);
} else {
throw new IllegalArgumentException("Target currency not available.");
}
} else if (toCurrency.equals(BASE_CURRENCY)) {
if (exchangeRates.containsKey(fromCurrency)) {
return amount / exchangeRates.get(fromCurrency);
} else {
throw new IllegalArgumentException("Source currency not available.");
}
} else {
if (exchangeRates.containsKey(fromCurrency) && exchangeRates.containsKey(toCurrency)) {
double usdAmount = amount / exchangeRates.get(fromCurrency);
return usdAmount * exchangeRates.get(toCurrency);
} else {
throw new IllegalArgumentException("Currency conversion not possible with provided data.");
}
}
}
public static void main(String[] args) {
// Creating the frame
JFrame frame = new JFrame("Cool Currency Converter");
frame.setSize(600, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.getContentPane().setBackground(new Color(45, 52, 54));
GridBagConstraints gbc = new GridBagConstraints();
gbc.insets = new Insets(10, 10, 10, 10);
// Creating and placing components with custom styling
JLabel labelAmount = new JLabel("Amount:");
labelAmount.setForeground(Color.WHITE);
labelAmount.setFont(new Font("Arial", Font.BOLD, 14));
gbc.gridx = 0;
gbc.gridy = 0;
frame.add(labelAmount, gbc);
JTextField textAmount = new JTextField(10);
textAmount.setFont(new Font("Arial", Font.PLAIN, 14));
textAmount.setBorder(new LineBorder(new Color(178, 190, 195), 2));
textAmount.setToolTipText("Enter the amount you want to convert");
gbc.gridx = 1;
gbc.gridy = 0;
frame.add(textAmount, gbc);
JLabel labelFromCurrency = new JLabel("From Currency:");
labelFromCurrency.setForeground(Color.WHITE);
labelFromCurrency.setFont(new Font("Arial", Font.BOLD, 14));
gbc.gridx = 0;
gbc.gridy = 1;
frame.add(labelFromCurrency, gbc);
String[] currencies = {"USD", "EUR", "GBP", "CHF"};
JComboBox<String> fromCurrencyComboBox = new JComboBox<>(currencies);
fromCurrencyComboBox.setFont(new Font("Arial", Font.PLAIN, 14));
fromCurrencyComboBox.setBorder(new LineBorder(new Color(178, 190, 195), 2));
gbc.gridx = 1;
gbc.gridy = 1;
frame.add(fromCurrencyComboBox, gbc);
JLabel labelToCurrency = new JLabel("To Currency:");
labelToCurrency.setForeground(Color.WHITE);
labelToCurrency.setFont(new Font("Arial", Font.BOLD, 14));
gbc.gridx = 0;
gbc.gridy = 2;
frame.add(labelToCurrency, gbc);
JComboBox<String> toCurrencyComboBox = new JComboBox<>(currencies);
toCurrencyComboBox.setFont(new Font("Arial", Font.PLAIN, 14));
toCurrencyComboBox.setBorder(new LineBorder(new Color(178, 190, 195), 2));
gbc.gridx = 1;
gbc.gridy = 2;
frame.add(toCurrencyComboBox, gbc);
JButton convertButton = new JButton("Convert");
convertButton.setFont(new Font("Arial", Font.BOLD, 14));
convertButton.setBackground(new Color(99, 110, 114));
convertButton.setForeground(Color.WHITE);
convertButton.setFocusPainted(false);
gbc.gridx = 1;
gbc.gridy = 3;
frame.add(convertButton, gbc);
JLabel resultLabel = new JLabel("");
resultLabel.setForeground(new Color(178, 190, 195));
resultLabel.setFont(new Font("Arial", Font.BOLD, 16));
gbc.gridx = 0;
gbc.gridy = 4;
gbc.gridwidth = 2;
frame.add(resultLabel, gbc);
// Live conversion as the user types
KeyAdapter keyAdapter = new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
try {
double amount = Double.parseDouble(textAmount.getText());
String fromCurrency = fromCurrencyComboBox.getSelectedItem().toString();
String toCurrency = toCurrencyComboBox.getSelectedItem().toString();
double convertedAmount = convertCurrency(amount, fromCurrency, toCurrency);
resultLabel.setText(amount + " " + fromCurrency + " = " + convertedAmount + " " + toCurrency);
} catch (NumberFormatException ex) {
resultLabel.setText("Please enter a valid number.");
} catch (IllegalArgumentException ex) {
resultLabel.setText(ex.getMessage());
}
}
};
textAmount.addKeyListener(keyAdapter);
fromCurrencyComboBox.addActionListener(e -> keyAdapter.keyReleased(null));
toCurrencyComboBox.addActionListener(e -> keyAdapter.keyReleased(null));
// Making the frame visible
frame.setVisible(true);
}
}