0

I have a java program that contain four classes, but I'll post two just to show my object interaction. After I run it I receive AWT-EventQueue-0" java.lang.NullPointerException I believe it because of my objects interaction. How to fix it?

public class myFrame extends JFrame {
    public PanelOne P1 = new PanelOne();
    public PanelTwo P2 = new PanelTwo();
    public myFrame mf;

    public myFrame() {
        super("MyFrame");
        setLayout(new BorderLayout());
        add(P1,BorderLayout.CENTER );
        add(P2,BorderLayout.EAST);
        setSize(600,500);
        setVisible(true);
    }
    public static void main(String args[]) {
        myFrame mf = new myFrame();
        mf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

public class PanelTwo extends JPanel {
    private myFrame mf;

    private JButton quit = new JButton("quit");
    private ButtonHandler bh = new ButtonHandler();

    private JRadioButton start = new JRadioButton("Start", true);
    private JRadioButton stop = new JRadioButton("Stop");
    private ButtonGroup group = new ButtonGroup();

    public PanelTwo(){
        super();
        setLayout(new GridLayout(9,1));
        setBackground(Color.RED);
        add(new JLabel("PanelTwo"));
        add(quit);
        quit.addActionListener(bh);
        add(start);
        add(stop);
        group.add(start);
        start.addActionListener(bh);
        group.add(stop);
        stop.addActionListener(bh);
    }
    public PanelTwo(myFrame mf){
        super();
        this.mf=mf;
    }
    public class ButtonHandler implements ActionListener {

        public void actionPerformed(ActionEvent ac){
            if(ac.getSource()==quit){
                System.exit(0);
            }
            if(ac.getSource()==stop){
                mf.P1.timer.stop();
            }
            if(ac.getSource()==start){
                mf.P1.timer.start();
            }
        }
    }
}

And this is what I got:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Sep16and2014.PanelTwo$ButtonHandler.actionPerformed(PanelTwo.java:45)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
.........

So, it said that my mistake starts in line with mf.P1.timer.stop(); I believe I somewhere assigned a null value. How to fix it?

Leistungsabfall
  • 6,368
  • 7
  • 33
  • 41
Manbran
  • 1
  • 5

2 Answers2

1

You are instantiating Panel2 with the empty constructor instead of passing it mf. You probably want this in myFrame:

  public myFrame mf;
  public PanelTwo P2 = new PanelTwo(mf);
Diego Basch
  • 12,764
  • 2
  • 29
  • 24
0

use a breakpoint to check what mf is. I suspect that mf is null because P1 was initialized with PanelTwo() ... not PanelTwo(mf)

fodon
  • 4,565
  • 12
  • 44
  • 58