基本textField actionListener错误(当命令在侦听器中时错误)



当我在文本字段上按enter键时,我一直得到一个错误(将在下面发布错误)。我希望文本字段将数据保存到一个全局定义的变量。actionListener工作时,我不包括'name'在我的代码,例如,如果我把a = 3,那么就没有错误。我还在全局(在主gui上)声明了名称,因为如果我不这样做,我会得到一个错误,说变量不在范围内,也许这是一个问题?

    //Declared inside the main gui (the others are nested in this)
    JTextField name;
    JLabel nameLabel;
    //Name text field defined inside the gui jInternalFrame
    TextField name = new TextField("Enter Name..", 20);
    JLabel nameLabel = new JLabel();
    nameLabel.setText("Name: ");
    name.addActionListener(new nameListener());
    addRoomPanel.add(nameLabel);
    addRoomPanel.add(name);`
    //ActionListener defined outside of the text field gui
    class nameListener implements ActionListener{
        public void actionPerformed(ActionEvent e){
            nameString = name.getText();
            name.setText("saved");
            name.selectAll();
         }
    }
ERROR MESSAGE:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at InternalFrame$dobListener.actionPerformed(InternalFrame.java:445)
    at java.awt.TextField.processActionEvent(TextField.java:617)
    at java.awt.TextField.processEvent(TextField.java:585)
    at java.awt.Component.dispatchEventImpl(Component.java:4872)
    at java.awt.Component.dispatchEvent(Component.java:4698)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:747)
    at java.awt.EventQueue.access$300(EventQueue.java:103)
    at java.awt.EventQueue$3.run(EventQueue.java:706)
    at java.awt.EventQueue$3.run(EventQueue.java:704)
    at java.security.AccessController.doPrivileged(Native Method)
    at  java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:720)
    at java.awt.EventQueue$4.run(EventQueue.java:718)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:717)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

UI的组件定义了两次。一次在gui类中作为变量,一次在(我想)构造函数中。由于存在两个名称为namenameLabel的变量。构造函数将访问在构造函数中声明的变量,因此gui类的变量保持未初始化(null)。ActionListener访问gui类中的变量null并抛出NullPointerException。你必须用一个变量而不是两个。为了得到更精确的答案,我需要更多的代码(或者至少比上面发布的代码片段更有用)。

相关内容

  • 没有找到相关文章

最新更新