这是我的代码:
JTable1.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent e) {
if (e.getButton() == MouseEvent.BUTTON1)
{
JTable target = (JTable)e.getSource();
Point pMouse = new Point();
pMouse = target.getMousePosition();
}
}
}
所以我正在检索相对于JTable的点(坐标)。因此,假设用户单击单元格中的某个位置,返回的Point为X = 272,Y = 50。所以现在我想用这些坐标精确定位JDialog。我试过了:
jDialog1.setLocation(pMouse);
jDialog1.setVisible(true);
但是这会将Dialog定位在其他位置(屏幕的坐标而不是表格)。有人建议如何将JDialog相对于单元格定位吗?
答案 0 :(得分:3)
您正在使用与JTable
内容的客户区相关的坐标。您需要与整个窗口相关的全局坐标。为此,您可以使用:
Point location = MouseInfo.getPointerInfo().getLocation();
jDialog1.setLocation(location);
答案 1 :(得分:0)
通常,用户应该能够通过鼠标或键盘使用您的应用程序。如果用户选中该单元格会发生什么?他们应该不能看到相同的对话吗?因此,无论您是否使用鼠标,都可以使用更通用的解决方案:
SwingUtilities.convertPointToScreen(point, table);
查看SwingUtilities中的其他convertXXX方法以供将来参考。
或者,您可以随时使用:
Component.getLocationOnScreen();
然后添加鼠标点。