本文介绍了使用JPanel的NullpointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

当我尝试在actionPerformed方法中调用panel2时,我得到了nullpointerexception.请帮助我摆脱这个愚蠢的问题.

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事件未与panel2关联,这是该异常背后的原因吗?

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

推荐答案

代替

next.addActionListener(new PanelEventTest());

您应该拥有

next.addActionListener(this);

否则,事件侦听器将是PanelEventTest的另一个 实例,该对象的originalFrame()方法从未被调用过,因此其panel2变量为null. (请注意,即使调用了其originalFrame()方法,它也会从其 own panel2中移除所有内容,而不是从包含按钮的框架的panel2中移除所有内容.)

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

这篇关于使用JPanel的NullpointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 00:40