我只想运行一个swing应用程序来显示一个文本字段。 以下是运行时生成的异常代码:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at textf.<init>(textf.java:10)
at textf$1.run(textf.java:35)
at java.awt.event.InvocationEvent.dispatch(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)
请帮忙做什么。
import java.awt.FlowLayout;
import javax.swing.*;
class textf{
JTextField tf;
JFrame j;
textf(){
new JFrame("TextField Demo");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setSize(400,200);
j.setLayout(new FlowLayout());
tf=new JTextField("press<Enter>",20);
j.add(tf);
j.setVisible(true);
}
public static void main(String s[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new textf();
}
});
}
}
答案 0 :(得分:3)
您永远不会为j
分配值,因此它的默认值为null
。当您尝试在构造函数的第二行(j.setDefaultCloseOperation(...)
)中取消引用它时,因此会抛出NullPointerException
。请注意,这是在您进入JTextField
...
只需将构造函数的第一行更改为:
j = new JFrame("TextField Demo");
之后,将代码缩进以及类和变量的命名进行排序,以便最终得到更易于维护的代码:)