我正在尝试画一个红绿灯。基本上是一个长方形框架,上面附有 4 个按钮。我已经按照给我的指示进行了操作,但我一定遗漏了一些东西。当我运行程序时,我得到:
Exception in thread "main" java.lang.NullPointerException
at TrafficLightPanel.<init>(TrafficLightPanel.java:14)
at TrafficLightApp.main(TrafficLightApp.java:11)
对此的任何帮助都会很棒^^
主要方法
import javax.swing.*;
public class TrafficLightApp {
public static void main(String[] args) {
JFrame frame = new JFrame("Traffic Lights");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
TrafficLightPanel lightPanel = new TrafficLightPanel(); //line 11
frame.add(lightPanel);//JFrame containing instance of TrafficLightPanel class
}
}
支持类
import javax.swing.*;
import java.awt.*;
public class TrafficLightPanel extends JPanel{
private JButton red,amber,green,change;
private JLabel buttonLabel,lastPressed;
private JPanel buttonPanel;
public TrafficLightPanel(){
//JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setSize(200,400);
panel.setBackground(Color.blue);
buttonPanel.setSize(80,390); //line 14
buttonPanel.setBackground(Color.white);
buttonPanel.add(red);
buttonPanel.add(amber);
buttonPanel.add(green);
buttonPanel.add(change);
buttonPanel.add(buttonLabel);
panel.add(buttonPanel);
}
}