1

我认为这更好。为什么标签文本没有改变?主类是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
            }
        }
4

1 回答 1

2

您的问题是,在您的 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 类中,传递this对可视化 JFrame 对象的引用:

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

这里的底线是甚至不要将这些人视为 JFrames 或 JPanels。只需将它们视为需要相互通信的类的对象,这通常通过公共方法完成。GUI 和非 GUI 程序没有什么不同。

于 2012-10-31T19:33:27.423 回答