有人提出了一个非常类似的问题here ,虽然我承认这一点,但问题的解决方案并不能完全解决我的问题。 JList
单击时,将选择距离鼠标单击最近的索引列表项。 JList
也会对每次单击+拖动事件触发执行此操作。
当单击+拖动位置位于可见列表之外时,我想阻止我的 JList
在单击+拖动事件期间选择项目。我该怎么办?
我曾考虑过重写一种不同的方法,该方法涉及选择列表项的单击+拖动事件。我想尝试一下 setSelectionInterval()
方法。
JList<String list = new JList<String>(){
private static final long serialVersionUID = 1L;
@Override
public int locationToIndex(Point location) {
int index = super.locationToIndex(location);
if (index != -1 && !getCellBounds(index, index).contains(location)) {
clearSelection();
return -1;
//an excellent click-only solution to prohibit the selecting of
//items from beyond the visible list
}
else {
return index;
}
}
@Override
public void setSelectionInterval(int anchor, int lead) {
super.setSelectionInterval(anchor, lead);
System.out.println("setSelectionInterval");
}
};
我发现每次单击并拖动显示的 JList
上的任意位置时,我都会收到添加到上述方法中的“setSelectionInterval”的 System.out 消息。我不知道在重写方法方面从这里该去哪里。也许这不是我应该采取的方式。在 setSelectionInterval()
的源代码中,我在尝试找到涉及的任何监听器的方法时迷失了方向,所以我来到了这里。 :p
我非常感谢任何有关我应该寻找的地方或解决方案的指示。提前致谢!
这是一个 SSCCE 示例,与我的设置方式很接近。事实上,当列表项本身触发仅单击事件时,列表将不会选择项目。我希望当单击+拖动事件从列表项中触发时也会发生相同的效果。
import java.awt.BorderLayout;
import java.awt.Point;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
public class TestMain {
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel content = new JPanel(new BorderLayout());
String[] data = {"Luke", "Jeff", "Bryce"};
JList<String> list = new JList<String>(data){
private static final long serialVersionUID = 1L;
@Override
public int locationToIndex(Point location) {
System.out.println("location to index");
int index = super.locationToIndex(location);
if (index != -1 && !getCellBounds(index, index).contains(location)) {
clearSelection();
return -1;
}
else {
return index;
}
}
}
content.add(list, BorderLayout.CENTER);
frame.setContentPane(content);
frame.setSize(200,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
最佳答案
如果禁用整个拖动功能是可以接受的,那么以下内容应该会有所帮助:
@Override
protected void processMouseMotionEvent(MouseEvent e) {
if(MouseEvent.MOUSE_DRAGGED != e.getID()) {
super.processMouseMotionEvent(e);
}
}
关于java - 当拖动超出其列表末尾时,如何防止 JList 选择元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16116517/