简体   繁体   English

Swing和标签setText不起作用

[英]Swing and label setText doesn't work

I need a little help with swing. 我需要一点帮助摆动。 This is my code: 这是我的代码:

public class UIdostawca extends javax.swing.JFrame {


    /** Creates new form UIdostawca */
    public UIdostawca() {
        initComponents();
        setDefaultCloseOperation(javax.swing.JFrame.HIDE_ON_CLOSE);
    }

    /* This is my function */
    public void loadStuff() {
        jLabel2.setText("Works or not?"); 
    }


    /*
      A lot of code generated by NETBEANS
     */


    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel2;

}

I use it like this: 我这样使用它:

UIdostawca a = new UIdostawca();

a.loadStuff();

and the jLabel2 didn't change ;( 并且jLabel2没有改变;(

However when in execute 但是在执行时

jLabel2.setText("Works or not?"); 

in function like formWindowOpened 在函数中像formWindowOpened

everything works 一切正常

It's a multi-threading issue. 这是一个多线程问题。 When formWindowOpened is called, it's called by the Swing event dispatch thread (EDT), which is the same thread that draws the interface, so it has the right value of text to draw. formWindowOpened ,它由Swing事件调度线程(EDT)调用,该线程与绘制接口的线程相同,因此它具有正确的文本值。

If you call setText from some other thread, the EDT will probably not get the right value for the text. 如果从其他某个线程调用setText ,则EDT可能无法获得正确的文本值。 Wherever you call setText in some other thread, you have to wrap it in a SwingUtilities.invokeLater() , which whill change the text value on the EDT. 无论你在其他某个线程中调用setText ,都必须将它包装在SwingUtilities.invokeLater() ,它会改变EDT上的文本值。

在第一种情况下,您是否初始化了jLabel2?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM