本文介绍了JList-从Click获得价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用ListSelectionListener或MouseAdapter获取有关所选值的信息(例如,如果value是一个String),是否有任何内置方法?

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?

我只知道如何获取正确的索引,但不知道content或content.toString()

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

我要添加这样的元素:

{
    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());
          }
    });

推荐答案

使用JList时,您只需使用 JList#getSelectedValue(),它将返回当前选定的实际对象.

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

如果从MouseListener内部执行此操作,最好使用 JList#locationToIndex ,然后使用JList的索引获取值

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()));

这篇关于JList-从Click获得价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 13:15