繁体   English   中英

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

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

我试图在jLabel和button所在的jLabel创建一个JFrame ,并在其中创建方法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!");
    }
}

当我按下按钮时,它不起作用。 它没有更改标签。 我正在使用netbeans 8.0。 这是我的完整代码

//NewJFrame.java

包test1;

公共类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                   

}

//NewClass.java

    package test1;

公共类NewClass {public void putTextNow(){
NewJFrame nf = new NewJFrame(); nf.jLabel1.setText(“ ok”); }}

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

在您的NewClass类中,您将创建一个NewJFrame的新实例。 您正在尝试更新当前JFrame没有的标签(您正在看到的标签)。 您必须从NewJFrame传递JLabel的引用,然后从那里进行更新:

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

NewClass变成

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

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

扩展Deutro所说的内容。 基本上,您想遵循MVC模式(模型,查看器,控制器)。

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

下面列出了如何设置MVC的模型。

首先是View类。

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

Model类(您的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();
        }

    });
}
}

您不需要多线程。 如果您的NewJFrame类具有名为jLabel1public JLabel ,则您发布的代码应该可以使用。

如前所述,您的代码应该已经可以工作了。 另外,您不应在NewJFrame类中将JLabel公开。 将其声明为私有,并使用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");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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