在单独的Thread中将组件添加到JFrame

时间:2014-03-13 02:43:18

标签: java multithreading swing jframe

我正在编写各种向导,并希望切换使用方法显示的内容。每次运行此代码时,都会出现空指针异常。

    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();
}

}

我做错了什么?

1 个答案:

答案 0 :(得分:2)

仔细阅读您的代码......

首先,您创建WizardScreen初始化

的实例
  • wizardFrame
  • contentPane

其次,你开始Thread ...

第三,你在welcomeScreen的实例上致电WizardScreen,这初始化......

  • title

然后尝试访问gridx的{​​{1}}属性...尚未初始化...

您应该检查c给您的信息......

NullPointerException

它清楚说明发生异常的地方,这对您和我们来说都是非常宝贵的信息。

请注意,Swing不是线程安全的,所有对UI的交互和修改都应该在Event Dispatching Thread的上下文中发生。见Concurrency in Swing

供参考:

通常建议您使用Exception in thread "main" java.lang.NullPointerException at eventdispatch.EventDispatch$WizardScreen.welcomeScreen(EventDispatch.java:52) at eventdispatch.EventDispatch.main(EventDispatch.java:20) pack,这应该在您致电setSize之前完成。还要注意,使用setVisible会改变窗口的大小......

setResizable(false)