【发布时间】:2014-03-13 02:43:17
【问题描述】:
我正在编写各种向导,并希望使用方法切换显示的内容。每次运行此代码时,都会出现空指针异常。
public class EventDispatch {
public static void main(String [] args){
WizardScreen wiz = new WizardScreen();
new Thread(wiz).start();
wiz.welcomeScreen();
}
}
public class WizardScreen implements Runnable{
protected JFrame wizardFrame;
protected JPanel contentPane;
protected JButton newQuote;
protected JButton openQuote;
protected JLabel title;
GridBagConstraints c;
public WizardScreen(){
wizardFrame = new JFrame();
contentPane = new JPanel(new GridBagLayout());
wizardFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
wizardFrame.setSize(550, 450);
wizardFrame.setResizable(false);
wizardFrame.setLocationRelativeTo(null);
wizardFrame.setTitle("Welcome!");
wizardFrame.setContentPane(contentPane);
wizardFrame.setVisible(true);
}
@Override
public void run() {
System.out.println("Running wizardScreen");
}
public void welcomeScreen(){
title = new JLabel("Welcome to ExSoft Quote Calculator Alpha 1.0");
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = .5;
contentPane.add(title, c);
wizardFrame.validate();
contentPane.repaint();
}
}
我做错了什么?
【问题讨论】:
-
您能否发布完整的异常堆栈跟踪,并告诉我们它指的是您代码中的哪一行。这对于尝试确定 NullPointerException 的原因很重要
-
“在单独的线程中向 JFrame 添加组件” - 我的第一个想法是,不要。 Swing 不是线程安全的。对 UI 的所有修改或交互都应在事件调度线程的上下文中进行。看看Concurrency in Swing
标签: java multithreading swing jframe