JList - getting value from Click

佐手、 提交于 2019-12-05 02:46:29

问题


Is there any way to use ListSelectionListener or MouseAdapter to get information about selected value (if value is a String for example), is there any built-in method for that?

I only know how to get proper indexes but not the content or content.toString()

I'm adding element like this:

{
    DefaultListModel listModel;

    listModel.addElement(name);
}

@Edit
Thank you for you for help. I solved my problem by doing this (for future generations so they wouldn't need to search as I did):

    list.addMouseListener(new MouseAdapter(){
          @Override
          public void mouseClicked(MouseEvent e) {
              System.out.println("Mouse click.");
              int index = list.getSelectedIndex();
              System.out.println("Index Selected: " + index);
              String s = (String) list.getSelectedValue();
              System.out.println("Value Selected: " + s.toString());
          }
    });

回答1:


When using a JList you can simply use JList#getSelectedValue() which will return the actual object that is current selected.

If you are doing this from within a MouseListener, it would be better to use JList#locationToIndex and then get the value from the JList using it's index

 String value = (String)list.getModel().getElementAt(list.locationToIndex(e.getPoint()));


来源:https://stackoverflow.com/questions/24234740/jlist-getting-value-from-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!