如何从java中的另一个类更新jLabel或setText?

如何从java中的另一个类更新jLabel或setText?,java,swing,class,methods,Java,Swing,Class,Methods,我试图创建一个JFrame,其中jLabel和button位于其中,另一个类在其中创建了一个方法putTextNow,该方法将文本设置为jLabel。我已经读到,它应该使用多线程来完成,这在我这方面更复杂。这是我的密码: NewJFrame.java private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { NewClass nc = new NewClass(); nc.putTextNow()

我试图创建一个JFrame,其中jLabel和button位于其中,另一个类在其中创建了一个方法putTextNow,该方法将文本设置为jLabel。我已经读到,它应该使用多线程来完成,这在我这方面更复杂。这是我的密码:

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!");
    }
}
    package test1;
当我按下按钮时,它不工作了。它不会改变标签。我正在使用netbeans 8.0。这是我的全部代码

//NewJFrame.java

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

公共类NewJFrame扩展了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                   
公共类新类{ 现在就公开募捐 { NewJFrame nf=新的NewJFrame; nf.jLabel1.setTextok; }
}

您不需要多线程。如果您的NewJFrame类具有
public JLabel,名称为jLabel1。

正如前面指出的那样,您的代码应该已经可以工作了。此外,您不应该在NewJFrame类中公开JLabel。将其声明为private,并使用getter和setter方法访问它。类似于以下内容:

public class NewJFrame extends JFrame{
    private JLabel myLabel;

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

    public void setMyLabel(String string) {
        myLabel.setText(string);
    }
}
现在,您可以使用以下设置标签:

nf.setMyLabel("Set my label to this string");
在NewClass类中,您正在创建NewJFrame的新实例。您正在尝试更新当前JFrame中没有的标签,即您正在看到的标签。您必须从NewJFrame传递JLabel的引用,然后从那里进行更新:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    NewClass nc = new NewClass();
    nc.putTextNow(myJLabel);
}
而新阶级变成了


如果我错了,请纠正我,但您似乎正在尝试创建一个包含JButton和JLabel的JFrame,并在单击按钮后更改文本

扩展Deutro所说的内容。基本上,您希望遵循MVC模式模型、查看器和控制器

这种模式的作用是将程序的各个部分分离为易于定义的元素,这些元素允许分离关注点,这似乎是您所尝试的

下面是如何设置MVC的模型

首先是视图类

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;
}
}
模型类为MVC提供了逻辑

package mvctest;

public class Model {

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

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

}
最后是控制器

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();
        }

    });
}
}

在新类中需要一个指向标签的引用:很遗憾,它不起作用。顺便说一句,这些是同一文件夹中的单独java文件。请告诉我什么不起作用。你有编译错误吗?或者运行的应用程序没有按预期工作吗?我的回答是:如果……也许你应该发布所有相关的代码都在你的问题中。也许这里的MVC模式有点太多了……他是一个初学者,正在使用NetBeans的内置函数来创建他的程序True,但是从长远来看,尽早学习保持关注点的分离应该会有所帮助。我最近还学习了java,在我学习了java的MVC基础知识之后UI应用程序它帮了我很大的忙,我直接去了MVC,因为他问的是MVC的路径,通过分离代码来修改另一个类中的标签文本。
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();
        }

    });
}
}