如何防止JList在单元格边界外进行选择? [英] How to prevent JList from making selection outside cell bounds?
问题描述
有什么方法可以阻止JList在用户点击列表下方的元素时选择最后一个元素吗?
这是有人问这里的问题,我有同样的问题。那个人发现了一个马马虎虎的解决方案(通过覆盖processMouseEvent()),但我想知道是否有更好/更优雅的方法来做到这一点。
That is the question someone asked here and I have the same problem. That guy found a so-so solution (by overriding processMouseEvent() ) but I want to know if there is a better/more elegant way to do it.
好的,更详细。
如果你有一个JList,并且有一些空间没有被任何单元/元素占用,你点击那个空格,那么JList中的最后一个元素就被选中了。
Ok, more detail. If you have a JList and there is some space unoccupied by any cell/element and you click that space then the last element in the JList got selected.
有关实际示例,请尝试 JList Swing Tutorial示例, 点击空格,看看Rollo已被选中。
For a real example try this JList Swing Tutorial example, click the white space and see that Rollo got selected.
推荐答案
参见 https://forums.oracle.com/forums/thread.jspa?threadID=2206996
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
public class TestJList {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JList list = new JList(new Object[] { "One", "Two", "Three" }) {
@Override
public int locationToIndex(Point location) {
int index = super.locationToIndex(location);
if (index != -1 && !getCellBounds(index, index).contains(location)) {
return -1;
}
else {
return index;
}
}
};
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
JList list = (JList) e.getSource();
if (list.locationToIndex(e.getPoint()) == -1 && !e.isShiftDown()
&& !isMenuShortcutKeyDown(e)) {
list.clearSelection();
}
}
private boolean isMenuShortcutKeyDown(InputEvent event) {
return (event.getModifiers() & Toolkit.getDefaultToolkit()
.getMenuShortcutKeyMask()) != 0;
}
});
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(new JScrollPane(list));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
这篇关于如何防止JList在单元格边界外进行选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!