[英]Make JList behave on click the same way as on ctrl+click?
我正在尋找一種方法來使JList
始終切換所單擊項目的選擇而不取消選擇其他項目,就像ctrl 單擊工作一樣。
ListSelectionModel
似乎是正確的方法,但我無法弄清楚那里必須配置什么。
如何使單擊的行為與ctrl 單擊相同的方式?
您可以使用以下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);
}
}
});
你必須自己創建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);
}
}
});
也許這段代碼可以正確地做到這一點
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();
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.