Java Swing JTable;右键单击菜单(如何让它“选择”又突出显示该行)
简而言之:我需要一个“右键单击事件”来突出显示单元格行。
我在 Java Swing (Netbeans Matisse) 的 ScrollPane 中使用 JTable。我在 JTable 上有一个 MouseClicked 事件侦听器,它执行以下操作:
if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
System.out.println("Right Click");
JPopUpMenu.show(myJTable, evt.getX(), evt.getY())
}
问题是...每当我在 JTable 上执行右键单击时,该行都不会突出显示(顺便说一句,我将选择设置为仅行)。我寻找了几个 setSelected() 函数,但找不到合适的函数。默认情况下,左键单击会自动突出显示该行。如何设置右键单击?
Short: I need a "right-click event" to highlight the cell row.
I am using a JTable inside a ScrollPane in Java Swing (Netbeans Matisse). I have a MouseClicked event listener on the JTable that does the following:
if (evt.getButton() == java.awt.event.MouseEvent.BUTTON3) {
System.out.println("Right Click");
JPopUpMenu.show(myJTable, evt.getX(), evt.getY())
}
The problem is... whenever I execute a right click on the JTable, the row isn't highlighted (I set the selection to rows only btw). I have looked for several setSelected() functions but could not find a suitable one. By default, left clicking automatically highlights the row. How do I set it up for right clicks?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
像这样:
......
like this:
......
接受的答案不考虑 ctrl 或 shift 等修饰键,但它们表明当前选择不应该被替换,而是应该被扩展。
此外,我还通过检查
mousePressed
和mouseReleased
添加了多操作系统支持。接下来,您可以找到有关如何使用
ListSelectionModel
,包括MouseEvent#getModifiers
检查。之后,可以打开一个(可选)<代码>JPopupMenu。The accepted answer does not take modifier keys like ctrl or shift into account, yet they indicate that the current selection should not be replaced, but extended.
Also, I added multi-OS support by checking
mousePressed
andmouseReleased
.Following, you can find a complete example on how to adjust the selected rows, using the
ListSelectionModel
, includingMouseEvent#getModifiers
checks. After that, it is possible to open a (optional)JPopupMenu
.您可以创建另一个 MouseEvent(此处的示例位于 JTable 子类中;
processMouseEvent()
具有受保护的访问权限,否则可以使用dispatchEvent()
方法)。负责使用修改器进行选择更新。You can create another MouseEvent (example here is in a JTable subclass;
processMouseEvent()
has protected access, otherwise could usedispatchEvent()
method). Takes care of using the modifiers for the selection update.