Week 13: Java Swing – Country Selector GUI
Objective: Create a simple GUI to select a country from a dropdown list and display it, with menu options to clear or exit.
Program: CountrySelector
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CountrySelector extends JFrame {
private JComboBox<String> countryComboBox;
public CountrySelector() {
// JFrame properties
setTitle("Country Selector");
setSize(400, 200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());
// Menu bar
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem clearItem = new JMenuItem("Clear");
JMenuItem exitItem = new JMenuItem("Exit");
fileMenu.add(clearItem);
fileMenu.add(exitItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
// Main panel with label, combo box, and button
JPanel mainPanel = new JPanel(new FlowLayout());
JLabel label = new JLabel("Choose a country:");
String[] countries = {"USA", "Canada", "Germany", "Japan", "Australia"};
countryComboBox = new JComboBox<>(countries);
JButton showButton = new JButton("Show Country");
mainPanel.add(label);
mainPanel.add(countryComboBox);
mainPanel.add(showButton);
add(mainPanel, BorderLayout.CENTER);
// Action listeners
clearItem.addActionListener(e -> countryComboBox.setSelectedIndex(0));
exitItem.addActionListener(e -> System.exit(0));
showButton.addActionListener(e -> {
String selectedCountry = (String) countryComboBox.getSelectedItem();
JOptionPane.showMessageDialog(this, "Selected Country: " + selectedCountry);
});
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> new CountrySelector().setVisible(true));
}
}
Key Features
- JFrame – The main window.
- JComboBox – Dropdown to select a country.
- JMenuBar, JMenu, JMenuItem – File menu with Clear and Exit options.
- JButton – Shows the selected country in a JOptionPane dialog.
-
ActionListener – Handles button and menu item clicks.
-
Clear: Resets combo box to first item.
- Exit: Closes the program.
- Show Country: Displays selected country in a pop-up.
GUI Layout
- Top: Menu bar (File → Clear, Exit)
-
Center: FlowLayout panel
-
Label:
"Choose a country:" - Dropdown: Country selection
- Button:
"Show Country"
Swing Notes
SwingUtilities.invokeLater()ensures the GUI runs on the Event Dispatch Thread (EDT).JOptionPane.showMessageDialog()is used to show pop-up messages.setSelectedIndex(0)resets the combo box selection.