The easiest and most straightforward way is to use the JPopupMenu
class. You can add any JComponent
to a JPopupMenu
, not just JMenuItem
s.
Here's a button which when clicked, shows a JList
in a popup without any close buttons, just with a scroll bar. Wherever the popup (the JList
) loses focus, the popup will be automatically closed.
final JButton b = new JButton("Press me");
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
final DefaultListModel<String> model = new DefaultListModel<>();
for (int i = 0; i < 100; i++)
model.addElement(i + ".");
final JList<String> l = new JList<>(model);
final JPopupMenu pm = new JPopupMenu();
final JScrollPane sp = new JScrollPane(l);
// pm.setPreferredSize(new Dimension(100, 300));
pm.add(sp);
pm.show(b, 0, 0);
}
});