Nullpointerexception with JPanel

2019-08-28 01:48发布

问题:

When I m trying to call panel2 inside actionPerformed method, I m getting nullpointerexception. Plz help me in getting out of this silly prblm.

public class PanelEventTest implements ActionListener {
    /**
     * @param args
     */
     JFrame frame;
     JPanel panel1, panel2;
     String[] list = {"Sachin","Tarun","Vipin"};
     JList jlist;
     JButton next;

     void originalFrame()
     {
         frame = new JFrame();
         frame.setSize(500, 300);
         frame.setVisible(true);
         frame.setLayout(new FlowLayout());
         frame.add(panel1());
         frame.add(panel2());
     }

     JPanel panel1()
     {
         panel1 = new JPanel();
         next = new JButton("Next");
         next.addActionListener(new PanelEventTest());
         panel1.add(next);
         return panel1;
     }

    JPanel panel2()
    {
         panel2 = new JPanel();
         jlist = new JList(list);
         panel2.add(jlist);
         panel2.add(new JLabel("Test"));
         return panel2;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new PanelEventTest().originalFrame();
    }


    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        if(e.getActionCommand() == "Next")
        {
            panel2.removeAll();
        }
    }
 }

action event is not attached with panel2, is that a reason behind this exception?

回答1:

Instead of

next.addActionListener(new PanelEventTest());

you should have

next.addActionListener(this);

Otherwise, the event listener will be another instance of PanelEventTest, whose originalFrame() method has never been invoked, and whose panel2 variable is thus null. (Note that even if its originalFrame() method was called, it would remove everything from its own panel2, and not from the panel2 of the frame containing the button).

You should prefer using (annonymous) inner classes for your listeners instead of making the frame itself a listener:

next.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        panel2.removeAll();
    }
});


回答2:

Maybe

next.addActionListener(this);