我正在写一些代码,现在画一个圆圈,稍后按下按钮时会移动圆圈。创建面板时,我希望已经在中心绘制了一个圆。我在actionPerformed方法中编写的代码在按下按钮时会这样做,但我希望在面板初始化时已经绘制好了,所以我将代码移到了createGUI方法中。然而,当我把它移到那里时,它不起作用,并且我得到了一个空指针异常。
有人能向我解释一下原因吗?谢谢
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MovingArrows extends JFrame implements ActionListener {
private JButton buttonUp, buttonDown, buttonLeft, buttonRight;
private JPanel panel;
private int xCircleCentre, yCircleCentre;
final int xCircleCentreStarting = 250, yCircleCentreStarting = 250;
final int RADIUS = 20;
public static void main(String[] args) {
// TODO Auto-generated method stub
MovingArrows frame = new MovingArrows();
frame.setSize(550, 600);
frame.createGUI();
frame.setVisible(true);
}
private void createGUI() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
Container window = getContentPane();
window.setLayout(new FlowLayout());
panel = new JPanel();
panel.setPreferredSize(new Dimension(500, 500));
panel.setBackground(Color.white);
window.add(panel);
buttonUp = new JButton("Up");
buttonDown = new JButton("Down");
buttonLeft = new JButton("Left");
buttonRight = new JButton("Right");
window.add(buttonUp);
window.add(buttonDown);
window.add(buttonLeft);
window.add(buttonRight);
buttonUp.addActionListener(this);
buttonDown.addActionListener(this);
buttonLeft.addActionListener(this);
buttonRight.addActionListener(this);
Graphics paper = panel.getGraphics();
paper.setColor(Color.black);
paper.fillOval(xCircleCentreStarting - RADIUS, yCircleCentreStarting
- RADIUS, RADIUS * 2, RADIUS * 2);
}
@Override
public void actionPerformed(ActionEvent event) {
/*
* Graphics paper = panel.getGraphics(); paper.setColor(Color.black);
* paper.fillOval(xCircleCentreStarting - RADIUS, yCircleCentreStarting
* - RADIUS, RADIUS * 2, RADIUS * 2);
*/
}
}
panel.getGraphics()返回null,因为组件尚未渲染。
另请参阅调用getGraphics()的任何替代方法,该方法返回空