[英]How to get the index of an Arraylist Through mouselistener?
I have putted the Arraylist into a JList and i want to get the value/index of the Arraylist when the mouse is clicked on the Jlist. 我已经将Arraylist放入JList中,并且当单击Jlist时,我想获得Arraylist的值/索引。 i have tried with these lines but it always shows -1 as index on the console for every elements clicked.
我已经尝试过使用这些行,但是对于单击的每个元素,它始终在控制台上显示-1作为索引。 here is the part of my code..
这是我的代码的一部分。
list2.addMouseListener(new MouseListener(){
public void mouseClicked(MouseEvent e){
JPanel MousePanel=new JPanel();
JList listp=new JList(PatientDetailArlist.toArray());
int index = listp.getSelectedIndex();
System.out.println("Index Selected: " + index);
String sp = (String) listp.getSelectedValue();
System.out.println("Value Selected: " + sp.toString());
MousePanel.add(listp);
tab.add("tab4",MousePanel);
visibleGui();
}
You add a MouseListener to "list2" which is your JList. 您将一个MouseListener添加到您的JList的“ list2”中。
list2.addMouseListener(new MouseListener(){
But then in your code for some reason you create a new JList? 但是由于某种原因,然后在代码中创建了新的JList? Well that JList is not visible on the GUI so there is no way it could have a selected index.
JList在GUI上不可见,因此它不可能具有选定的索引。
JList listp=new JList(PatientDetailArlist.toArray());
int index = listp.getSelectedIndex();
All you need in the listener code is: 您在侦听器代码中所需的全部是:
int index = list2.getSelectedIndex();
Or even better is to get the JList component that was clicked from the MouseEvent: 甚至更好的方法是获取从MouseEvent单击的JList组件:
JList list = (JList)e.getSource();
int index = list.getSelectedIndex();
However, that is still not a good solution. 但是,这仍然不是一个好的解决方案。 What if the user uses the keyboard to select an item?
如果用户使用键盘选择一个项目怎么办? A proper design of a GUI should allow the user to use the mouse or the keyboard.
GUI的正确设计应允许用户使用鼠标或键盘。
So you should not be using a MouseListener. 因此,您不应该使用MouseListener。 Instead you should be using a ListSelectionListener to listen for changes in selection of an item in the list.
相反,您应该使用ListSelectionListener侦听列表中项目的选择更改。
Read the section from the Swing tutorial on How to Write a ListSelectionListener for more information and examples to get you started. 阅读Swing教程中有关如何编写ListSelectionListener的部分 ,以获取更多信息和示例,以帮助您入门。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.