我正在尝试按照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);
}
}
我做错了什么?
答案 0 :(得分:4)
您应该将监听器添加到面板。
插入以下构造函数:
public TheJPanel() {
this.addMouseMotionListener(this);
}
答案 1 :(得分:1)
我认为您需要添加:
addMouseListener(y);
addMouseMotionListener(y);