0

I'm trying to draw a traffic light. Basically a long rectangle shaped frame with 4 buttons attached to it. I've followed the instructions I've been given but I must be missing something. When I run the program I get:

Exception in thread "main" java.lang.NullPointerException
    at TrafficLightPanel.<init>(TrafficLightPanel.java:14)
    at TrafficLightApp.main(TrafficLightApp.java:11)

Any help on this would be great ^^

Main method

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

    }

}

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

1 に答える 1

4

You're using a lot of null variables, just because the reference variables declared at the top, does not mean they magically have an instance assigned to them, you still need to make JComponent Objects.

Since you instantiate panel but don't also instantiate buttonPanel, that's your first NPE. You also don't instantiate your JButtons, you simply add them to your buttonPanel, same thing with buttonLabel and lastPressed (but this var is unused).

Also, keep in mind that TrafficLightPanel is already a JPanel, you may be able to get rid of some redundancy.

So, basically you have to instantiate (using the new keyword) each and every variable declared at the top before you use it. Positioning will also be an issue, but it's not your current problem.

于 2013-02-04T01:37:07.397 に答える