In my Java Swing application, I show a list of options to users using a JOptionPane with a JList, using the code below:
List<Object> options = getOptions();
JList list = new JList(options.toArray());
JScrollPane scrollpane = new JScrollPane();
JPanel panel = new JPanel();
panel.add(scrollpane);
scrollpane.getViewport().add(list);
JOptionPane.showMessageDialog(null, scrollpane,
"Please select an object", JOptionPane.PLAIN_MESSAGE);
How can I let the user select an option by double-clicking it?
JList
doesn't provide any special handling of double or triple (or N) mouse clicks, but it's easy to add a MouseListener
if you wish to take action on these events. Use the locationToIndex
method to determine what cell was clicked. For example:
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int index = list.locationToIndex(e.getPoint());
System.out.println("Double clicked on Item " + index);
}
}
});
I just need to know how to close the dialog after the user double-clicks the item
In this mouse event, you can make use of SwingUtilities.windowForComponent(list)
to get the window and dispose it using window.dispose()
function.