我正在创建一个简单的程序,它可以在鼠标所在的任何位置绘制(显示)我的图像。所以图像随着鼠标箭头移动。
为此,我创建了 aJFrame
并通过名为 的类将 a 添加到MouseMotionListener
其中。使用类添加图像。Image
Frame
imageComponent
在MouseMotionListener
我获取鼠标坐标但无法理解如何为方法提供这些x
和y
坐标paintComponent
,以及每次移动鼠标时如何重新绘制它。这是我的代码:
main()
类中的方法Practice
:
public class Practice {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable(){
public void run(){
JFrame frame = new Frame();
frame.setSize(500,500);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
});
}
}
Frame
将侦听器添加ImageComponent
到框架的类。
class Frame extends JFrame{
Frame(){
add(new imageComponent());
addMouseMotionListener(new MouseAdapter(){
public void mouseMoved(MouseEvent me){
int x = me.getX();
int y = me.getY();
repaint();
}
});
}
}
imageComponent
类,从指定路径绘制图像:
class imageComponent extends JComponent{
Image img;
int x,y;
imageComponent(){
img = new ImageIcon("C:\\Users\\Kaushal28\\Desktop\\image.png").getImage();
}
public void paint(Graphics g){
g.drawImage(img, x, y, null);
}
}
在上面的类中,我声明了x
and y
:鼠标坐标。我想从听众那里得到,但不明白如何做到这一点。请有人帮忙!
编辑:
如果我添加mouseMotionListener
,imageComponent
那么它会给出这个错误: