美好的一天!我试验过Swing和AWT,我偶然发现了java.swing.JFrame和java.awt.event.MouseListener。
基于以下代码:
Game.java
(...)
public Game() {
frame = new JFrame();
ih = new IH();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
(...)
frame.add(this);
frame.addMouseListener(ih);
}
IH.java
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
public class IH implements MouseListener {
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX());
System.out.println(e.getY());
System.out.println("Got clicked");
}
public void mouseEntered(MouseEvent e) { }
public void mouseExited(MouseEvent e) { }
public void mousePressed(MouseEvent e) { }
}
我还没有从控制台收到任何输出,但我也没有收到任何错误。我希望在JFrame中点击的位置接收x和y坐标。我怎样才能做到这一点?或者,在JFrame中不可能这样吗?那我该怎么用?
答案 0 :(得分:1)
在本地测试它并按预期工作。你用frame.add(this)
添加了什么?
public class Test {
public static void main(String[] args) {
JFrame t = new JFrame();
t.setSize(500, 500);
t.addMouseListener(new IH());
t.show();
}
public static class IH implements MouseListener{
@Override
public void mouseClicked(MouseEvent e) {
System.out.println(e.getX());
System.out.println(e.getY());
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}
}