我正在尋找一種方法來使JList
始終切換所選項目的選擇而不取消其他人的選擇,如同ctrl點擊的作品。使JList的行爲點擊與按Ctrl +單擊相同的方式?
ListSelectionModel
似乎是正確的路要走,但我不明白什麼必須在那裏配置。
如何使一個JList上點擊以同樣的方式表現爲對CTRL點擊?
我正在尋找一種方法來使JList
始終切換所選項目的選擇而不取消其他人的選擇,如同ctrl點擊的作品。使JList的行爲點擊與按Ctrl +單擊相同的方式?
ListSelectionModel
似乎是正確的路要走,但我不明白什麼必須在那裏配置。
如何使一個JList上點擊以同樣的方式表現爲對CTRL點擊?
你必須讓自己的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);
}
}
});
這是我經常發現的代碼片段,但它只增加了切換,如果點擊所選項目 – Philippe
否它會像ctrl那樣工作。 – SilentBomb
你是對的,抱歉沒有正確測試 – Philippe
也許這個代碼可以做到這一點正確
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();
}
});
}
謝謝,那可能有效。我會記住,如果我需要假鑰匙:) – Philippe
您可以使用以下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);
}
}
});
謝謝!我一直在尋找這個網頁的一段時間 – Philippe
見我的回答一個相關的問題在這裏: http://stackoverflow.com/questions/2528344/jlist-deselect-when-clicking-an-already-selected-item/9196431#9196431 – FuryComputers