首页 > 代码库 > Component creation must be done on Event Dispatch Thread错误解决方法

Component creation must be done on Event Dispatch Thread错误解决方法

在用java swing 做例子,给页面设置皮肤样式的时候出现了这个错误:

org.jvnet.substance.api.UiThreadingViolationException: Component creation must be done on Event Dispatch Thread
    at org.jvnet.substance.utils.SubstanceCoreUtilities.testComponentCreationThreadingViolation(SubstanceCoreUtilities.java:2368)
    at org.jvnet.substance.SubstancePanelUI.createUI(SubstancePanelUI.java:57)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:243)
    at javax.swing.UIDefaults.getUI(UIDefaults.java:751)
    at javax.swing.UIManager.getUI(UIManager.java:1016)
    at javax.swing.JPanel.updateUI(JPanel.java:109)
    at javax.swing.JPanel.<init>(JPanel.java:69)
    at javax.swing.JPanel.<init>(JPanel.java:92)
    at javax.swing.JPanel.<init>(JPanel.java:100)
    at javax.swing.JRootPane.createGlassPane(JRootPane.java:527)
    at javax.swing.JRootPane.<init>(JRootPane.java:347)
    at javax.swing.JFrame.createRootPane(JFrame.java:260)
    at javax.swing.JFrame.frameInit(JFrame.java:241)
    at javax.swing.JFrame.<init>(JFrame.java:164)
    at com.chat.frame.ClientLoginFrame.<init>(ClientLoginFrame.java:52)
    at com.chat.frame.ClientLoginFrame.main(ClientLoginFrame.java:241)

 

   后来查了很多资料,发现是由于swing 的线程不安全引起的,

解决方案如下:

在main方法里,程序的主入口加上:

 SwingUtilities.invokeLater(new Runnable() {  
                public void run() {  
                    
                    new ClientLoginFrame().setVisible(true); //这个就是程序界面初始化
                }  
            });  

 

这样问题就解决。