简体   繁体   中英

Can not write ActionListener in JButton

Please help me solve my problem. My problems are with this code in java .

button.addActionListener(new ActionListener() {     
   public void actionPerformed(ActionEvent arg0) {               
        text.append("hello\n");
   }
}); 

and error is :

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at swing.Mainframe.<init>(Mainframe.java:23)
at swing.Swing$1.run(Swing.java:11)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$400(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)     

Write this before you code:

button = new JButton();

It seems like your variable isn't been initialized yet.

Or either the text variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM