我是Java的初学者,我正在尝试创建一个在光标所在位置绘制矩形的应用程序。我已经完成了所有工作,但我无法mouseMoved(MouseEvent) method
重新绘制JPanel
. 没有重绘,矩形只绘制一次,仅此而已。通过重绘,它编译得很好,但是当我运行它时,每次移动鼠标时,我都会得到这个大的“ Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
”错误。
那么,有人可以帮我解决这个问题吗?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.event.*;
public class Game extends JPanel implements MouseMotionListener
{
public static void main(String[] args) {
new Game().game();
}
JPanel panel;
JButton button2;
JButton button;
public void game() {
JPanel panel = new Game();
button = new JButton("Ok");
panel.setLayout(new FlowLayout());
panel.add(button);
button2 = new JButton("Cancel");
JFrame frame = new JFrame("Game");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setResizable(false);
frame.add(panel);
frame.setVisible(true);
panel.addMouseMotionListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
PointerInfo a = MouseInfo.getPointerInfo();
Point b = a.getLocation();
int x = (int) b.getX();
int y = (int) b.getY();
g.fillRect(x,y,100,100);
}
public void mouseMoved(MouseEvent evt) {
panel.repaint; //This is the line of code that I need help with. Thanks!
}
public void mouseDragged(MouseEvent evt) {}
}