user3955353
user3955353

Reputation:

How to update jLabel or setText from another class in java?

I am trying to create one JFrame where the jLabel and button are located and another class where I have created a method putTextNow that will set the text to the jLabel. I have read that it should be done using multithreading which is more complicated in my part. Here are my codes:

NewJFrame.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    NewClass nc = new NewClass();
    nc.putTextNow();
}

NewClass.java

package test1;

public class NewClass {
    public void putTextNow () {
        NewJFrame nf = new NewJFrame();
        nf.jLabel1.setText("OK!");
    }
}

When I press the button, it's not working. It's not changing the Label. I'm using netbeans 8.0. Here are my full codes

//NewJFrame.java

package test1;

public class NewJFrame extends javax.swing.JFrame {

public NewJFrame() {
    initComponents();
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    jLabel1.setText("jLabel1");

    jButton1.setText("jButton1");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(114, 114, 114)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createSequentialGroup()
                    .addGap(23, 23, 23)
                    .addComponent(jButton1)))
            .addContainerGap(179, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(96, 96, 96)
            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(43, 43, 43)
            .addComponent(jButton1)
            .addContainerGap(65, Short.MAX_VALUE))
    );

    pack();
}// </editor-fold>                        

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    NewClass nc = new NewClass();
    nc.putTextNow();
}                                        

public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    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(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new NewJFrame().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
public javax.swing.JButton jButton1;
public javax.swing.JLabel jLabel1;
// End of variables declaration                   

}

//NewClass.java

    package test1;

public class NewClass { public void putTextNow () {
NewJFrame nf = new NewJFrame(); nf.jLabel1.setText("ok"); } }

Upvotes: 0

Views: 32327

Answers (4)

Fos
Fos

Reputation: 53

Correct me if I am wrong, but it seems that you are trying to create a JFrame that contains a JButton and a JLabel. And make the text change once you click the button.

To expand on what Deutro has said. Basically you want to follow a MVC patter (Model, Viewer, Controller).

What this pattern does is seperate the portions of the program into easily defined elements that allow seperation of concern, this seems to be what you have attempted.

A mockup of how to set out the MVC is below.

Firstly the View class.

package mvctest;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import javax.swing.JButton;

public class View extends JFrame {

private JLabel lblNewLabel;
private JButton btnNewButton;

public View() {

    lblNewLabel = new JLabel("New label");
    getContentPane().add(lblNewLabel, BorderLayout.NORTH);

    btnNewButton = new JButton("New button");
    getContentPane().add(btnNewButton, BorderLayout.SOUTH);
}

public JButton getBtnNewButton() {
    return btnNewButton;
}

public JLabel getLblNewLabel() {
    return lblNewLabel;
}
}

The Model class (The logic for your MVC)

package mvctest;

public class Model {

private View view;
public Model(View view) {
    this.view = view;
}

public void changeText() {
    view.getLblNewLabel().setText("Changed text");
}

}

And finally the Controller

package mvctest;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Controller {

public Controller() {
    View view = new View();
    Model model = new Model(view);
    view.getBtnNewButton().addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            model.changeText();
        }

    });
}
}

Upvotes: 4

Narmer
Narmer

Reputation: 1454

NewJFrame nf = new NewJFrame();
nf.jLabel1.setText("OK!");

In your NewClass class you are creating a new instance of NewJFrame. You are trying to update a label which is not in your current JFrame (the one you are seeing). You have to pass a reference of your JLabel from NewJFrame and update from there:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    NewClass nc = new NewClass();
    nc.putTextNow(myJLabel);
}

and NewClass becomes

public class NewClass {
    public void putTextNow (JLabel label) {
        label.setText("OK!");
    }
}

Upvotes: 4

Deutro
Deutro

Reputation: 3313

As already pointed out your code should already work. Additionally you should not make your JLabel public in the NewJFrame class. Declare it as private and access it with getter and setter methods. Something like this:

public class NewJFrame extends JFrame{
    private JLabel myLabel;

    public String getMyLabel() {
        return myLabel.getText();
    }

    public void setMyLabel(String string) {
        myLabel.setText(string);
    }
}

Now you can set your label with:

nf.setMyLabel("Set my label to this string");

Upvotes: 2

Kai
Kai

Reputation: 39631

You don't need multithreading. The code you've posted should work if your NewJFrame class has a public JLabel with the name jLabel1.

Upvotes: 1

Related Questions