我是Java初學者,我試圖創建一個應用程序,該應用程序在光標所在的位置繪製一個矩形。我已經完成了所有工作,但是我無法使mouseMoved(MouseEvent) method
重新繪製JPanel
。沒有重繪,矩形只能繪製一次,就是這樣。隨着重畫,它編譯好,但是當我運行它,每次移動鼠標,我得到這個大「Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
」錯誤。Java - 重繪JPanel給出錯誤
那麼,任何人都可以請幫我一下嗎?
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) {}
}
1)使用代碼塊的一致和邏輯縮進。代碼的縮進旨在幫助人們理解程序流程。 2)不要設置頂級容器的大小。而是佈置內容並調用'pack()'。 –
感謝您的評論安德魯。但是如果我不調整JFrame的大小,那麼它將如何知道窗口的大小? pack()是做什麼的?再次感謝! –
*「pack()是做什麼的?」*如果您已經閱讀了該方法的JavaDocs,則很可能您不必提出這些問題! –