0

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?

Ricardo
  • 748
  • 12
  • 26

2 Answers2

3

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.

Sage
  • 15,290
  • 3
  • 33
  • 38
  • Almost there! Now, to completely solve my problem, I just need to know how to close the dialog after the user double-clicks the item (from within mouseClicked event, I suppose). But how? – Ricardo Nov 27 '13 at 18:55
  • +1, answers the OP's question, but the user should be able to use the mouse or the keyboard. – camickr Nov 27 '13 at 18:56
  • @camickr, i have just checked your added link. quite a nice work. I will look into the source of `ListAction` class. +1 to you for now :) – Sage Nov 27 '13 at 19:02
  • @Ricardo, you can look into the camickr's linked class too. It will be useful to you in future when you will like to work with KeyBoard too :) – Sage Nov 27 '13 at 19:04
3

See List Action for a solution that will allow you to select an Item from the list with the mouse or the keyboard.

In the Action that you create you can use:

Window window = SwingUtilities.windowForComponent(...);

to get the window that you need to dispose();

camickr
  • 321,443
  • 19
  • 166
  • 288