我正在尝试使特定的文本字符串跟随 JPanel 内的光标。我创建了一个扩展 JPanel 并实现 MouseMotionListener 的类。该代码似乎不起作用。显示文本,但不跟随光标。
package followthemouse;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
public class TheJPanel extends JPanel implements MouseMotionListener {
private int x = 20;
private int y = 20;
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawString("I love your cursor!", x, y);
}
@Override
public void mouseMoved (MouseEvent me)
{
x = me.getX();
y = me.getY();
repaint();
}
@Override
public void mouseDragged (MouseEvent me)
{
}
}
这是主要功能中的内容:
package followthemouse;
import javax.swing.JFrame;
/**
*
* @author Vikram
*/
public class FollowTheMouse extends JFrame{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
TheJPanel y = new TheJPanel();
JFrame x = new JFrame("The TITLE");
x.add(y);
x.setSize(400, 400);
x.setVisible(true);
}
}
我究竟做错了什么?