我开始使用Swing创建一个桌面应用程序,我完全是新手。因为我没有在语法或结构中发现任何错误但它会引发错误。这只是一个活动演示程序。
package testEvent;
import java.awt.FlowLayout;
import java.awt.event.*;
import javax.swing.*;
public class EventDemo {
JLabel jlab;
EventDemo(){
JFrame jfrm = new JFrame("An Event Example");
jfrm.setLayout(new FlowLayout());
jfrm.setSize(220,90);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton jbtnAlpha = new JButton("Alpha");
JButton jbtnBeta = new JButton("Beta");
jbtnAlpha.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
jlab.setText("Alpha was Pressed.");
}
});
jbtnBeta.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
jlab.setText("Beta was Pressed.");
}
});
jfrm.add(jlab);
jfrm.setVisible(true);
}
public static void main(String args[]){
//Create the Frame on Event Dispatching thread
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new EventDemo();
}
});
}
}
抛出以下错误
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at testEvent.EventDemo.<init>(EventDemo.java:40)
at testEvent.EventDemo$3.run(EventDemo.java:49)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)*
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(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)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
答案 0 :(得分:5)
您需要初始化JLabel jlab。像下面这样的东西应该做。
JLabel jlab = new JLabel();