我制作了一个完美编译但显示运行时错误的程序。我已经搜索过这些错误,但没有找到这个错误。
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
class swing11
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new mainframe();
}
});
}
}
import javax.swing.JFrame;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class mainframe extends JFrame{
private JTextArea textarea;
private JButton btn;
public mainframe(){
super("new program");
setLayout(new BorderLayout());
btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent arg0){
textarea.append("hello\n");
}
});
textarea =new JTextArea();
btn = new JButton("click me!");
add(textarea, BorderLayout.CENTER);
add(btn, BorderLayout.SOUTH);
setSize(500,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
}
错误:
---------- run ----------
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at mainframe.<init>(mainframe.java:16)
at swing11$1.run(swing11.java:11)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:727)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:688)
at java.awt.EventQueue$3.run(EventQueue.java:686)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:697)
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)
Output completed (1 sec consumed) - Normal Termination
答案 0 :(得分:2)
您需要在btn
之前分配addActionListener
。