我想知道列表中使用的多选功能是否也可以在对象中使用?
我发现的例子是从链接提供的列表上工作。 https://stackoverflow.com/questions/25691623/jlist-listselectionlistener-multiple-interval-selection-that-waits-for-cntrl-or
我正在研究的当前项目是绘制不同的形状,这是一个对象。完成绘图后,我可以通过按住SHIFT键选择多个对象。
我该怎么做?
答案 0 :(得分:0)
您无法以简单的方式重复使用List-Selection-Model - 我真的建议您使用自己的实现。
为此,您必须在Panel上添加KeyListener和MouseListener,以检查是否按下了Shift。
private boolean isShiftDown = false;
KeyAdapter ka = new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
super.keyReleased(e);
if(e.getKeyCode() == KeyEvent.VK_SHIFT){
isShiftDown=false;
}
}
@Override
public void keyPressed(KeyEvent e) {
super.keyPressed(e);
if(e.getKeyCode() == KeyEvent.VK_SHIFT){
isShiftDown=true;
}
}
};
使用您自己的选择'模型',这将是一个简单的列表(java.util.List)
private List<Shape> selectionList = new ArrayList();
MouseAdapter ma = new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
Shape shape = findShapeAt(e.getX(), e.getY() ); //i guessed you had a methode like that
if (shape != null){
//check is your shift key is down
if (isShiftDown){
//add or remove on click
if (selectionList.contains(shape) ){
selectionList.remove(shape);
}else{
selectionList.add(shape);
}
}else{
//if shift is NOT down, clear the list before adding
selectionList.clear();
selectionList.add(shape);
}
}
//show the selection in your gui();
updateSelection(); //that's your part - draw a nice border around all Shapes from the selectionList
}
};
不要忘记将两个 keyListener(KeyAdapter)和MouseListener(MouseAdapter)添加到面板中......
我真的会使用 ctrl-key (KeyEvent.VK_CONTROL)代替 shift-key 来通过单击鼠标来添加/删除形状...