简体   繁体   English

JList - 从Click获取值

[英]JList - getting value from Click

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? 有没有办法使用ListSelectionListener或MouseAdapter来获取有关所选值的信息(例如,如果值是一个字符串),是否有任何内置方法?

I only know how to get proper indexes but not the content or content.toString() 我只知道如何获取正确的索引但不知道内容或内容.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()); } }); 

When using a JList you can simply use JList#getSelectedValue() which will return the actual object that is current selected. 使用JList您只需使用JList#getSelectedValue() ,它将返回当前选中的实际对象。

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 如果您是在MouseListener中执行此操作,最好使用JList#locationToIndex ,然后使用它的索引从JList获取值

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM