0

I am learning Java from HeadFirst Java. When I run the app, it shows the circle first. But when I click the Button, it fires the below error. Below is the code and error:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI implements ActionListener {
JFrame frame;

public static void main(String[] args) {
    GUI g = new GUI();
    g.go();
}

private void go() {
    JFrame frame = new JFrame("Title");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JButton button = new JButton("Change Color");
    button.addActionListener(this);

    MyWidget my = new MyWidget();

    frame.getContentPane().add(BorderLayout.SOUTH, button);
    frame.getContentPane().add(BorderLayout.CENTER, my);
    frame.setSize(300, 300);
    frame.setVisible(true);

}

@Override
public void actionPerformed(ActionEvent e) {
    frame.repaint();
}
}
class MyWidget extends JPanel {
@Override
public void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g;
    int red = (int) (Math.random() * 255);
    int green = (int) (Math.random() * 255);
    int blue = (int) (Math.random() * 255);
    Color startColor = new Color(red, green, blue);
    red = (int) (Math.random() * 255);
    green = (int) (Math.random() * 255);
    blue = (int) (Math.random() * 255);
    Color endColor = new Color(red, green, blue);
    GradientPaint gradient = new GradientPaint(70, 70, startColor, 150, 150, endColor);
    g2.setPaint(gradient);  
    g2.fillOval(70, 70, 100, 100);
}  
}

Here is what I getting on console:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at HeadFirstJava.GUI.actionPerformed(GUI.java:32)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
durron597
  • 31,968
  • 17
  • 99
  • 158
Saeed Jassani
  • 1,079
  • 2
  • 11
  • 27
  • 1
    You're shadowing your `frame` variable. You define `frame` as a class instance field; `JFrame frame;`, but then you declare a local variable in your `go` method; `JFrame frame = new JFrame("Title");`. Remove the local redeceleration; `frame = new JFrame("Title");` – MadProgrammer Aug 28 '15 at 04:42

1 Answers1

3

Your JFrame is not in scope when you first declare it. Change this line:

JFrame frame = new JFrame("Title");

to this:

frame = new JFrame("Title");
durron597
  • 31,968
  • 17
  • 99
  • 158