我希望能够使我的 JList 响应单击,即使多次按下也是如此。仅当单击另一个索引时才调用更改的值。这是默认行为。但是,我希望它始终告诉当点击发生时。从这个简单的例子中,很明显,只有单击一次,更改的值才会被触发,单击两次将不会响应。我需要这个特定的功能,主要原因是合法的,但解释起来更复杂.
public class TestFrame extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestFrame frame = new TestFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(new BorderLayout(0, 0));
JList list = new JList();
list.setModel(new AbstractListModel() {
String[] values = new String[] {"one", "two", "three"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
list.addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
// TODO Auto-generated method stub
System.out.println("selected index : "+list.getSelectedIndex());
}
});
contentPane.add(list, BorderLayout.CENTER);
}
}
最佳答案
您需要使用 MouseListener 来解决此问题:
list.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
int index = list.locationToIndex(e.getPoint());
System.out.println("MouseListener index: " + index);
}
});
关于java - Java中无论点击Jlist多少次,如何从Jlist中获取选定的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29061999/