Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import java.awt.BorderLayout;
import java.awt.Component;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;

public class Main {
    public static final void main(String[] args) {
        JFrame frame = new JFrame();

        JPanel mainPanel = new JPanel();
        JPanel buttonsPanel = new JPanel();
        frame.add(mainPanel);
        frame.add(buttonsPanel, BorderLayout.SOUTH);

        String[] options = { "S", "G", "I", "T" };

        JComboBox comboBox = new JComboBox(options);
        comboBox.setRenderer(new MyComboBoxRenderer("COUNTRY"));
        comboBox.setSelectedIndex(-1);
        mainPanel.add(comboBox);

        JButton clearSelectionButton = new JButton("Clear selection");
        clearSelectionButton.addActionListener(e -> {
            comboBox.setSelectedIndex(-1);
        });
        buttonsPanel.add(clearSelectionButton);

        frame.pack();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class MyComboBoxRenderer extends JLabel implements ListCellRenderer {
    private String _title;

    public MyComboBoxRenderer(String title) {
        _title = title;
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
            boolean hasFocus) {
        if (index == -1 && value == null)
            setText(_title);
        else
            setText(value.toString());
        return this;
    }
}