I'm fairly new to code, and I'm attempting to complete and assignment requires a smiley face to move around the screen (in this case it should move around the center panel). I'm just starting the basics of the code and getting the action to work just once (i.e. push the button and one smiley shows up), but I'm having trouble. This is what I have so far:
public class AllSmiles extends JApplet implements ActionListener
JPanel topPanel, centerPanel;
public void init()
h = 400;
w = 430;
JPanel topPanel = new JPanel(new FlowLayout());
push = new JButton("Push");
JPanel centerPanel = new JPanel(new FlowLayout());
public void paint(Graphics g)
private void stampSmiley(Graphics g, int x, int y, int size, Color color)
g.fillOval(x+6, y+7, 6, 6);
g.fillOval(x+18, y+7, 6, 6);
g.fillOval(x+5, y+15, 20, 8);
g.fillOval(x+6, y+13, 18, 8);
private void delay(int ms)
public void actionPerformed(ActionEvent e)
Graphics g = centerPanel.getGraphics();
The code compiles with no issue, but when asked to run it does nothing and I get "Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException" in Line 71.
If I change the line to
Graphics g = this.getGraphics();
then it stamps the smiley in the north panel... but if I change "this" to either centerPanel or topPanel, it does nothing and I get the same null issue.
What is it that I'm doing wrong? I've been searching all over the internet and I never quite understand the responses to similar issues (clearly, I'm very new at this...)
Thanks in advance for any help!