面板 - 为什么我不能将代码移动到另一个方法?

时间:2013-12-16 12:08:05

标签: java graphics

我正在编写一些代码,此刻会绘制一个圆圈,然后在按下按钮时移动圆圈。创建面板后,我想在中心绘制一个圆圈。我在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);
         */
    }
}

1 个答案:

答案 0 :(得分:0)

panel.getGraphics()返回null,因为组件尚未呈现。

另见Any alternative to calling getGraphics() which is returning null