Display text to a label from another class - JFrame

前端 未结 5 558
感情败类
感情败类 2021-01-16 22:45

I have a GUI screen, and it has a label in it. I now want to set the label with a text as i have shown in below (Test). But it\'s not getting updated. I think t

相关标签:
5条回答
  • 2021-01-16 23:27

    Change the mainScreen() function to

    public  void mainScreen() {
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    try {
                        setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    

    remaining code is same

    0 讨论(0)
  • 2021-01-16 23:44

    Add a method to your FrameTest

    public String readLabel(){
           return this.lblLabel.getText();
    }
    
    0 讨论(0)
  • 2021-01-16 23:47

    In your mainScreen() you create a new FrameTest that is distinct from the one you create in the main routine, so it's actually changing the text, of the invisible frame. Try this instead:

    private FrameTest frame = this;
    
    public  void mainScreen() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                    frame.setVisible(true);
            }
        });
    }
    

    Or simply:

    public  void mainScreen() {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                    setVisible(true);
            }
        });
    }
    
    0 讨论(0)
  • 2021-01-16 23:47

    Replace the try block with;

                try {
                    setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
    

    Everything works!

    0 讨论(0)
  • 2021-01-16 23:49

    The way you use your code does not trigger a repaint of your frame or label. In Swing you can change many Gui Objects, but they are only redrawn in a single batch when requested. The most usual case when a repaint occurs automatically, is after you return from an event handler. (E.g. a button click or key press)

    0 讨论(0)
提交回复
热议问题