Skip to content

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

  1. JFrame – The main window.
  2. JComboBox – Dropdown to select a country.
  3. JMenuBar, JMenu, JMenuItem – File menu with Clear and Exit options.
  4. JButton – Shows the selected country in a JOptionPane dialog.
  5. ActionListener – Handles button and menu item clicks.

  6. Clear: Resets combo box to first item.

  7. Exit: Closes the program.
  8. 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.

Comments