Java 获取鼠标相对于帧的X、Y坐标
我有一个按钮,当我在按钮上使用鼠标时,我想知道鼠标x,y坐标相对于框架的坐标 如何才能做到这一点?注册并实现相应的事件。MouseEvent有getX和getY方法,可以为您提供鼠标位置。注册并实现相应的事件。MouseEvent有getX和getY方法,可以为您提供鼠标位置。Java 获取鼠标相对于帧的X、Y坐标,java,events,Java,Events,我有一个按钮,当我在按钮上使用鼠标时,我想知道鼠标x,y坐标相对于框架的坐标 如何才能做到这一点?注册并实现相应的事件。MouseEvent有getX和getY方法,可以为您提供鼠标位置。注册并实现相应的事件。MouseEvent有getX和getY方法,可以为您提供鼠标位置。getBounds()提供一个带有按钮相对于其父按钮的位置和尺寸的矩形。在我的示例中,父对象是JFrame public class Click { public static void main(String[
getBounds()
提供一个带有按钮相对于其父按钮的位置和尺寸的矩形。在我的示例中,父对象是JFrame
public class Click {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame f = new JFrame("Click pos");
f.setSize(640, 480);
final JButton b = new JButton("Click Me!");
b.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
final JButton bb = (JButton) e.getSource();
final Rectangle bbox = bb.getBounds();
final int x = bbox.x + e.getX();
final int y = bbox.y + e.getY();
JOptionPane.showMessageDialog(f, "pos: " + x + " " + y);
}
});
f.getContentPane().add(b, BorderLayout.SOUTH);
f.setVisible(true);
}
});
}
}
编辑:
有了SwingUtilities的helper方法,mouseClicked
方法变得简单多了。您可以获得正确的坐标,这与JFrame
和JButton
之间的容器数量无关。我不知道他们
final JButton bb = (JButton) e.getSource();
Point p = SwingUtilities.convertPoint(bb, e.getPoint(), f);
JOptionPane.showMessageDialog(f, p);
getBounds()
为您提供一个带有按钮相对于其父按钮的位置和尺寸的矩形。在我的示例中,父对象是JFrame
public class Click {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final JFrame f = new JFrame("Click pos");
f.setSize(640, 480);
final JButton b = new JButton("Click Me!");
b.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
final JButton bb = (JButton) e.getSource();
final Rectangle bbox = bb.getBounds();
final int x = bbox.x + e.getX();
final int y = bbox.y + e.getY();
JOptionPane.showMessageDialog(f, "pos: " + x + " " + y);
}
});
f.getContentPane().add(b, BorderLayout.SOUTH);
f.setVisible(true);
}
});
}
}
编辑:
有了SwingUtilities的helper方法,mouseClicked
方法变得简单多了。您可以获得正确的坐标,这与JFrame
和JButton
之间的容器数量无关。我不知道他们
final JButton bb = (JButton) e.getSource();
Point p = SwingUtilities.convertPoint(bb, e.getPoint(), f);
JOptionPane.showMessageDialog(f, p);
是的,但当我在按钮中时,JFrame不会触发该事件在按钮的事件侦听器中尝试以下代码:PointerInfo a=MouseInfo.getPointerInfo();点b=a.getLocation();intx=(int)b.getX();int y=(int)b.getY();不,它给我的坐标是相对于按钮的坐标,而不是相对于框架的坐标!签出SwingUtilities类。它有用于转换鼠标事件坐标的辅助方法,以及用于转换相对于组件和屏幕的点的其他实用方法。是的,但当我在按钮中时,JFrame不会触发该事件在按钮的事件侦听器中尝试以下代码:PointerInfo a=MouseInfo.getPointerInfo();点b=a.getLocation();intx=(int)b.getX();int y=(int)b.getY();不,它给我的坐标是相对于按钮的坐标,而不是相对于框架的坐标!签出SwingUtilities类。它有用于转换鼠标事件坐标的辅助方法,以及用于转换相对于组件和屏幕的点的其他实用方法。