如何从java中的另一个类更新jLabel或setText? [英] How to update jLabel or setText from another class in java?

查看:174
本文介绍了如何从java中的另一个类更新jLabel或setText?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 JFrame ,其中找到了 jLabel 和按钮以及我创建的另一个类一个方法 putTextNow ,它将文本设置为 jLabel 。我已经读过它应该使用多线程来完成,这在我看来更复杂。以下是我的代码:

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

NewJFrame.java

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

NewClass.java

NewClass.java

package test1;

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

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

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

//NewJFrame.java

package test1;

package test1;

公共类NewJFrame扩展javax.swing.JFrame {

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

//NewClass.java

    package test1;

public class NewClass {
public void putTextNow()
{

NewJFrame nf = new NewJFrame();
nf.jLabel1.setText(ok);
}
}

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

推荐答案

如果我错了,请纠正我,但似乎你正试图创建一个包含JButton和JLabel的JFrame。单击按钮后,可以更改文本。

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.

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

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.

如何设置MVC的模型如下。

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

首先是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的逻辑)

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

}

最后控制器

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中的另一个类更新jLabel或setText?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆