为什么我收到actionPerformed()错误:未知来源?

时间:2015-08-28 04:38:37

标签: java swing

我正在从HeadFirst Java学习Java。当我运行应用程序时,它首先显示圆圈。但是,当我单击按钮时,它会触发以下错误。以下是代码和错误:

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);
}  
}

以下是我在控制台上的内容:

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)

1 个答案:

答案 0 :(得分:2)

首次声明时,您的JFrame不在范围内。改变这一行:

frame = new JFrame("Title");

到此:

{{1}}