I'm writing some code that at the moment draws a circle and later will move the circle when buttons are pressed. When the panel is created, I want to have a circle already drawn in the centre. The code I've written in the actionPerformed method does this when a button is pressed, but I wanted this to be already drawn when the panel initialises so I moved the code to the createGUI method. However, it doesn't work when I move it there and I get a null pointer exception.
Could someone please explain to me why? Thanks.
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);
*/
}
}