如何通过innerclass itemListener修改类变量?

时间:2014-04-07 14:36:45

标签: java awt inner-classes itemlistener

我在这里有以下代码:

public class A extends Runnable {
  ArrayList<String> choosenFiles;

  run(){
  /*graphic stuff such as JFrame,JLabel,JButtons*/
  }

  private ButtonListener implements ActionListener {
  /*options*/
  }

  public class cbListener implements ItemListener {
    @Override
    public void itemStateChanged(ItemEvent e) {
        Checkbox cb = (Checkbox)e.getItemSelectable();
        String cbl = cb.getLabel();

        if (e.getStateChange() == ItemEvent.SELECTED) {
            JOptionPane.showMessageDialog(null, "selected:\n" + cbl);
            choosenFiles.add(cbl);
        } else if (e.getStateChange() == ItemEvent.DESELECTED) {
            JOptionPane.showMessageDialog(null, "deselected:\n" + cbl);
            choosenFiles.remove(cbl);
        }
    }
}  

问题似乎是CBListenerchoosenFile出现而无法达到AWT-EventQueue-0 java.lang.NullPointerException

这是stacktrace:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at FileDownloader.Client.User$cbListener.itemStateChanged(Unknown Source)
at java.awt.Checkbox.processItemEvent(Checkbox.java:563)
at java.awt.Checkbox.processEvent(Checkbox.java:530)
at java.awt.Component.dispatchEventImpl(Component.java:4660)
at java.awt.Component.dispatchEvent(Component.java:4488)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:674)
at java.awt.EventQueue.access$400(EventQueue.java:81)
at java.awt.EventQueue$2.run(EventQueue.java:633)
at java.awt.EventQueue$2.run(EventQueue.java:631)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege
(AccessControlContext.java:87)
at java.security.AccessControlContext$1.doIntersectionPrivilege
(AccessControlContext.java:98)
at java.awt.EventQueue$3.run(EventQueue.java:647)
at java.awt.EventQueue$3.run(EventQueue.java:645)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege
(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:644)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

有没有办法解决这个问题?

1 个答案:

答案 0 :(得分:2)

看起来choosenFiles尚未初始化;这应该在早期发生,例如在构造函数或初始化方法中。 此外,最好使用尽可能最通用的界面,因此,如果choosenFiles没有很好的理由被定义为ArrayList<String>,请将其设为List<String>