使JList的行为与ctrl + click相同?

时间:2011-11-01 10:27:07

标签: java swing jlist

我正在寻找一种让JList始终切换所点击项目的选择而不取消选择其他项目的方法,就像 ctrl 点击工作。

ListSelectionModel似乎是正确的方法,但我无法弄清楚那里必须配置什么。

如何使单击上的JList行为与 ctrl 上单击相同?

3 个答案:

答案 0 :(得分:5)

您可以使用以下ListSelectionModel

list.setSelectionModel(new DefaultListSelectionModel(){
    @Override
    public void setSelectionInterval(int start, int end) {
        if (start != end) {
            super.setSelectionInterval(start, end);
        } else if (isSelectedIndex(start)) {
            removeSelectionInterval(start, end);
        } else {
            addSelectionInterval(start, end);
        }
    }
});

答案 1 :(得分:4)

你必须制作自己的ListSelectionModel。试试吧。

list.setSelectionModel(new DefaultListSelectionModel() 
{
    @Override
    public void setSelectionInterval(int index0, int index1) 
    {
        if(list.isSelectedIndex(index0)) 
        {
            list.removeSelectionInterval(index0, index1);
        }
        else 
        {
            list.addSelectionInterval(index0, index1);
        }
    }
});

答案 2 :(得分:2)

也许这段代码可以正确地做到

import java.awt.Component;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import javax.swing.*;

public class Ctrl_Down_JList {

    private static void createAndShowUI() {
        String[] items = {"Sun", "Mon", "Tues", "Wed", "Thurs", "Fri", "Sat"};
        JList myJList = new JList(items) {

            private static final long serialVersionUID = 1L;

            @Override
            protected void processMouseEvent(MouseEvent e) {
                int modifiers = e.getModifiers() | InputEvent.CTRL_MASK;
                // change the modifiers to believe that control key is down
                int modifiersEx = e.getModifiersEx() | InputEvent.CTRL_MASK;
                // can I use this anywhere?  I don't see how to change the modifiersEx of the MouseEvent
                MouseEvent myME = new MouseEvent((Component) e.getSource(), e.getID(), e.getWhen(), modifiers, e.getX(),
                        e.getY(), e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), e.getButton());
                super.processMouseEvent(myME);
            }
        };
        JFrame frame = new JFrame("Ctrl_Down_JList");
        frame.add(new JScrollPane(myJList));
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                createAndShowUI();
            }
        });
    }