Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import javax.swing.plaf.basic.BasicComboPopup;

public class Main extends JFrame {
    public Main() {
        String[] items = { "Item1", "Item2", "Item3", "Item4", "Item5" };
        JComboBox<String> comboBox = new JComboBox<>(items);
        add(comboBox);

        comboBox.addPopupMenuListener(new PopupMenuListener() {
            public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
                JComboBox<String> comboBox = (JComboBox<String>) e.getSource();
                BasicComboPopup popup = (BasicComboPopup) comboBox.getAccessibleContext().getAccessibleChild(0);
                JList list = popup.getList();
                list.setSelectedIndex(2);
            }

            public void popupMenuCanceled(PopupMenuEvent e) {
            }

            public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
            }

        });
    }

    public static void main(String[] args) {
        Main frame = new Main();
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}