JLabel变量已更新,但GUI未更新

时间:2016-11-30 03:23:14

标签: java swing user-interface awt

当我运行应该从JLabel获取文本的代码时,使用getter方法将其移动到按钮动作类,修改它然后使用setter方法在原始类中设置它,它更新JLabel变量,但更新GUI。

我在标签,框架和包含标签的面板上尝试过repaint(),revalidate(),doLayout()。

初始化标签的类:

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.BorderLayout;
import java.awt.event.ActionListener;

import javax.swing.JLabel;
import javax.swing.SwingConstants;
import javax.swing.JButton;

public class Testing4 {

    private JFrame frame;
    private JLabel lblNewLabel;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Testing4 window = new Testing4();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Testing4() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 450, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        lblNewLabel = new JLabel("label");
        lblNewLabel.setBounds(52, 101, 277, 53);
        frame.getContentPane().add(lblNewLabel);
        lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);

        JButton btnNewButton = new JButton("New button");
        btnNewButton.setBounds(114, 28, 156, 53);
        frame.getContentPane().add(btnNewButton);
        btnNewButton.addActionListener(new ButtonAction());
    }

    public String getLabelText()
    {
        return this.lblNewLabel.getText();
    }

    public void setLabelText(String text)
    {
        System.out.println(text);

        this.lblNewLabel.setText(text);

        System.out.println(lblNewLabel.getText());
    }

}

如果查看setLabelText(String)方法,它会将文本设置为名为lblNewLabel的标签,然后在下一行代码中将文本打印到控制台。 .getText()显示标签已被修改,但GUI未显示它已被修改。

以下是按钮的代码:

public class ButtonAction implements ActionListener
    {
        Testing4 test;

        public void actionPerformed(ActionEvent e) 
        {

            test = new Testing4();

            String x = test.getLabelText();

            System.out.println(x);

            x = x + " hello";

            System.out.println(x);

            test.setLabelText(x);


        }


}

对于所有意图和目的,这应该使用新文本更新GUI,我之前已经完成了这个并没有出现问题,但这次出现了问题。

0 个答案:

没有答案