java 如何从 JPANEL(子窗体)设置 JFRAME(父窗体)中标签的文本

标签 java swing constructor jframe jpanel

我认为这更好。为什么标签文本没有改变? 主类采用NewJFrame形式

public class NewJFrame extends javax.swing.JFrame {
        public NewJFrame() {
            initComponents();
            NewJPanel jpanel = new NewJPanel();
            anotherPanel.add(jpanel);
         //there is also a label in this frame outside of the anotherPanel
        }
    }

这是一个 JPanel 表单。我正在将此 jpanel 添加到 NewJFrame (anotherPanel)

public class NewJPanel extends javax.swing.JPanel {
        public NewJFrame newJFrame;
            public NewJPanel() {
                initComponents();
                this.setSize(200, 200);
        //there is a button here
            }
   private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
                this.newJFrame = newJFrame;
      newJFrame.jLabel1.setText("Need To change the text from here"); // this is not working, text is not changing
            }
        }

最佳答案

您的问题是,在 JPanel 代码中,您正在创建一个与正在显示的 JFrame 完全不同的新 JFrame 对象,如下所示:

public NewJPanel() {
 NewJFrame newfr = NewJFrame();  // *** here ***

因此调用 NewJFrame 方法或设置其字段将不会对可视化 GUI 产生明显影响。

要解决此问题,您必须对要更改其行为的类(此处为 NewJFrame 类)的可行引用调用方法。因此,您必须将此类的引用传递到 NewJPanel 类中(也许是在其构造函数中),以便 NewJPanel 类可以调用实际显示的 NewJFrame 对象上的方法。

例如:

public class NewJPanel extends javax.swing.JPanel {  
  private NewJFrame newJFrame;

  // pass in the current displayed NewJFrame reference when calling this constructor
  public NewJPanel(NewJFrame newJFrame) {
    this.newJFrame = newJFrame;
    newJFrame.setMyLabelText("qqqqqq");
  }          
}

然后在 NewJFrame 类中,传递对可视化 JFrame 对象 this 的引用:

public NewJFrame() {
  NewJPanel pane= new NewJPanel(this); 

这里的底线是不要将这些家伙视为 JFrame 或 JPanel。只需将它们视为需要相互通信的类的对象,这通常是通过公共(public)方法完成的。对于 GUI 程序和非 GUI 程序来说没有什么不同。

关于java 如何从 JPANEL(子窗体)设置 JFRAME(父窗体)中标签的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13166166/

相关文章:

java - MSIL 可以转换为 Java native 代码吗?

java - 如何从第一行是标题,其他行是相关数据的文本文件中读取和存储数据

java - JTextPane 超出了 JDialog 的边界

java - 为参数化构造函数获取值的方法

java - 为什么 Heroku 上的 org.kie#kie-spring;6.1.0.Final 构建失败?

java - 将自定义方法添加到 JButton 类

java - 使用较旧的 java 版本运行 swing 应用程序

java - Swing 中的外观和感觉

java - 构造函数方法尝试从子类初始化insatnce变量得到StackOverflowError

Python __init__ 语法