Jack Twain
Jack Twain

Reputation: 6372

Why multiple selection on JList acts like a right click mouse?

I'm adding a MouseListener to a JList so that when a right click is made, then I clear the selection from the JList. But I allow the JList to be able to handle interval selection. When I select using control button and select randomly some items from the list, then the MouseEvent is fired! But when I do continuos selection using Shift key, then it works fine!

Here is my code:

List.addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent e)
            {
                JList list = (JList) e.getSource();
                if ( SwingUtilities.isRightMouseButton(e) ) {
                    System.out.println("Boom");
                    list.clearSelection();
                }
            }
});

Upvotes: 0

Views: 590

Answers (1)

lol
lol

Reputation: 3390

SSCCEE mean Short, Self Contained, Correct (Compilable), Example. You should create one short example which demonstrates your problem. Your actual code can be long and unnecessary to show problem, so you should create small running program.

Ok, so here is SSCCE, and as expected its working fine. Let here know, what problem you are facing when you go with this example.

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class ListDemo extends JFrame{
    private DefaultListModel<String> listModel;
    private JList<String> list;
    private JScrollPane listScrollPane;

    public ListDemo(){
        listModel = new DefaultListModel<String>();
        for(int i = 0; i < 10; i++){
            listModel.addElement("Item " + (i + 1));
        }

        list = new JList<String>(listModel);
        list.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent me){
                if(SwingUtilities.isRightMouseButton(me)){
                    list.clearSelection();
                }
            }
        });

        listScrollPane = new JScrollPane(list);

        getContentPane().add(listScrollPane);

        setSize(500, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String [] arg){
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ListDemo().setVisible(true);
            }
        });
    }
}

Upvotes: 1

Related Questions