Java 在单独的线程中将组件添加到JFrame
我正在编写一个排序向导,希望使用方法切换显示内容。每次运行这段代码时,我都会得到一个空指针异常Java 在单独的线程中将组件添加到JFrame,java,multithreading,swing,jframe,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 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();
}
}
我做错了什么?浏览一下您的代码 首先,创建一个
WizardScreen
初始化的实例
wizardFrame
contentPane
线程
第三,在WizardScreen
的实例上调用welcomeScreen
,这将初始化
标题
c
的gridx
属性,该属性尚未初始化
您应该检查NullPointerException
提供给您的信息
Exception in thread "main" java.lang.NullPointerException
at eventdispatch.EventDispatch$WizardScreen.welcomeScreen(EventDispatch.java:52)
at eventdispatch.EventDispatch.main(EventDispatch.java:20)
它清楚地说明了异常发生的位置,这对您和我们来说都是非常宝贵的信息
注意,Swing不是线程安全的,对UI的所有交互和修改都应该在事件调度线程的上下文中发生。看
供参考:
通常建议使用setSize
的pack
,这应该在调用setVisible
之前最后一次完成。还要注意,使用setresizeable(false)
会更改窗口的大小
wizardFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//wizardFrame.setSize(550, 450);
//wizardFrame.setResizable(false);
//wizardFrame.setLocationRelativeTo(null);
wizardFrame.setTitle("Welcome!");
wizardFrame.setContentPane(contentPane);
wizardFrame.setResizable(false);
wizardFrame.pack();
wizardFrame.setLocationRelativeTo(null);
wizardFrame.setVisible(true);
您能否发布完整的异常堆栈跟踪,并告诉我们它指的是代码中的哪一行。这在试图确定NullPointerException“在单独的线程中向JFrame添加组件”的原因时很重要——我的第一个想法是,不要这样做。Swing不是线程安全的。对UI的所有修改或交互都应该在事件调度线程的上下文中进行。看看