How to get the index of an Arraylist Through mouselistener?

595 Views Asked by At

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. i have tried with these lines but it always shows -1 as index on the console for every elements clicked. 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();
                }
1

There are 1 best solutions below

0
camickr On

You add a MouseListener to "list2" which is your JList.

list2.addMouseListener(new MouseListener(){

But then in your code for some reason you create a new JList? Well that JList is not visible on the GUI so there is no way it could have a selected index.

 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:

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.

So you should not be using a MouseListener. Instead you should be using a ListSelectionListener to listen for changes in selection of an item in the list.

Read the section from the Swing tutorial on How to Write a ListSelectionListener for more information and examples to get you started.