我试图在面板中显示鼠标坐标,但每次移动光标时,消息和新坐标都显示在前一个上。我正在使用带有JPanel的MouseMotionListener。我无法弄清楚问题。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.event.MouseMotionListener;
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
public static void main(String[] args) {
new Main();
JFrame frame = new JFrame();
frame.setTitle("MouseCoordinates");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(new Main());
frame.setVisible(true);
}
public Main() {
setSize(400, 400);
label = new JLabel("No Mouse Event Captured", JLabel.CENTER);
add(label);
addMouseMotionListener(this);
}
public void mouseMoved(MouseEvent e) {
label.setText("Mouse Cursor Coordinates => X:" + e.getX() + " |Y:" + e.getY());
}
public void mouseDragged(MouseEvent e) {}
}
答案 0 :(得分:1)
您正在创建Main
两次。
public class Main extends JPanel implements MouseMotionListener {
public JLabel label;
public static void main(String[] args) {
Main m = new Main();// create an object and reference it
JFrame frame = new JFrame();
frame.setTitle("MouseCoordinates");
frame.setSize(400, 400);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
Container contentPane = frame.getContentPane();
contentPane.add(m);
frame.setVisible(true);
}
//...
你的问题是两次创建Main
对象(这是一个jpanel)然后写了两次。如果您为Main
对象提供参考,那么您的问题应该得到解决。