简体   繁体   中英

Changing the JLabel text from another class doesn't work

I have two classes MainFrame and Test . MainFrame class contains two components a JButton and a JLabel .

I want the text of JLabel to be changed when I invoke setText() method from Test class by creating an instance of MainFrame in Test class, when I click the JButton . But unfortunately neither the setText() nor the getText() work from Test class. How can I achieve it?

Here's my code.

MainFrame.java :

    public class MainFrame extends javax.swing.JFrame {

    public MainFrame() {
        initComponents();
    }

    private void initComponents() {

        labelToSet = new javax.swing.JLabel();
        clickMeButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        labelToSet.setText("Hello");

        clickMeButton.setText("Click me");
        clickMeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clickMeButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(84, Short.MAX_VALUE)
                .addComponent(clickMeButton)
                .addGap(50, 50, 50)
                .addComponent(labelToSet)
                .addGap(110, 110, 110))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(98, 98, 98)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(labelToSet)
                    .addComponent(clickMeButton))
                .addContainerGap(79, Short.MAX_VALUE))
        );

        pack();
    }                       

    /*Code to be concentrated*/
    private void clickMeButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
        Test t = new Test();
    }                                             

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }

    public javax.swing.JButton clickMeButton;
    public javax.swing.JLabel labelToSet;                   
}

Test.java :

public class Test {

    Test() {
        MainFrame mf = new MainFrame();
        System.out.println(mf.labelToSet.getText());
        mf.labelToSet.setText("Goodbye!");
    }
}

You are changing the text of labelToSet in a different instance of the class MainFrame , an instance that is never shown on screen.

If you want your code in the constuctor of Test to change the text of the label that is already being shown, you need to pass it a reference to that MainFrame object.

Change your Test constructor to accept that reference:

public class Test {
    Test(MainFrame mf) {
        mf.labelToSet.setText("Goodbye!");
    }
}

And call it accordingly (passing the reference this to the MainFrame object that is currently being shown):

private void clickMeButtonActionPerformed(java.awt.event.ActionEvent evt) {
    Test t = new Test(this);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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