gpt4 book ai didi

java - 鼠标坐标不断叠加-Java

转载 作者:行者123 更新时间:2023-11-30 10:37:00 24 4
gpt4 key购买 nike

我试图让鼠标坐标显示在面板中,但每次我移动光标时,消息和新坐标都会显示在前一个上。我正在将 MouseMotionListener 与 JPanel 一起使用。我无法找出问题所在。

enter image description here

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) {}
}

最佳答案

您正在创建 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 对象一个引用,那么您的问题应该得到解决。

关于java - 鼠标坐标不断叠加-Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40308932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com