右键单击整个 JTable 组件上的 MouseListener
我正在使用 Netbeans,并且使用 JTable 设计了一个窗口,并在 JTable 组件上添加了 MouseEvent 侦听器,并添加了以下代码:
private void productsTableMousePressed(java.awt.event.MouseEvent evt) {
if(evt.isPopupTrigger()) {
tablePopupMenu.setLocation(evt.getXOnScreen(), evt.getYOnScreen());
tablePopupMenu.setVisible(true);
System.out.println("Fired!");
}
}
private void productsTableMouseReleased(java.awt.event.MouseEvent evt) {
if(evt.isPopupTrigger()) {
tablePopupMenu.setLocation(evt.getXOnScreen(), evt.getYOnScreen());
tablePopupMenu.setVisible(true);
}
}
但它仅在我单击某些单元格时才起作用。我想让它在整个 JTable 区域上工作。如何?
I'm using Netbeans and I've designed a window with JTable and added MouseEvent listener on JTable component and added this code:
private void productsTableMousePressed(java.awt.event.MouseEvent evt) {
if(evt.isPopupTrigger()) {
tablePopupMenu.setLocation(evt.getXOnScreen(), evt.getYOnScreen());
tablePopupMenu.setVisible(true);
System.out.println("Fired!");
}
}
private void productsTableMouseReleased(java.awt.event.MouseEvent evt) {
if(evt.isPopupTrigger()) {
tablePopupMenu.setLocation(evt.getXOnScreen(), evt.getYOnScreen());
tablePopupMenu.setVisible(true);
}
}
But it works only when I click on some cells. I want to get it working on whole JTable area. How?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您的表格位于 JScrollPane 内,它可能不会覆盖整个视口。要确保覆盖视口的整个区域,请调用
setFillsViewportHeight(true)
在您的桌子上。Assuming your table is inside a JScrollPane, it may not cover the entire viewport. To ensure the whole area of your viewport is covered, call
setFillsViewportHeight(true)
on your table.MouseListener 将在所有单元格上起作用。我不知道您是否应该使用 setLocation(...) 方法。
有关示例代码,请参阅调出弹出菜单。
或者更好的方法是使用:
The MouseListener will work on all cells. I don't know if you should be using the setLocation(...) method.
See Bringing Up a Popup Menu for example code.
Or a better approach is to use:
我发现在我的 JTable(位于 JScrollPane 中,嵌套在 JInternalFrame 中)中,当 JTable 大于 JScrollPane 时,滚动和调整大小可能会出现问题。
基本上,如果框架位于我的左侧显示器上,但我已将表格一直滚动到右侧,则弹出窗口会出现在我的右侧显示器上。
我查看了四种不同选项的结果:
框架和滚动窗格的 getMousePositions(),以及鼠标事件 getX 和 getXOnScreen()。
唯一给我想要的结果的是框架的 getMousePositions() 。其他一切都被它自己的内部世界观所抵消,这对我来说是有道理的。
所以我想我要说的是要小心你获取鼠标坐标的位置。
I've found that in my JTable (which is in a JScrollPane, nested in a JInternalFrame), there can be issues with scrolling and resizing when the JTable was larger than the JScrollPane.
Basically, if the Frame is on my left monitor, but I've scrolled the table all the way to the right, the pop-up appears on my right monitor.
I reviewed the results of four different options:
the getMousePositions() for both the frame and the scroll pane, plus the mouse event getX and getXOnScreen().
The only one that gave me the results I wanted was the getMousePositions() for the frame. Everything else was offset by it's own internal view of the world, which makes sense to me.
So I guess what I'm saying is be careful where you get your mouse coordinates.