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

ここでの結論は、これらの人をJFrameやJPanelsとは考えないことです。それらを相互に通信する必要のあるクラスのオブジェクトと考えてください。これは通常、パブリックメソッドを介して行われます。GUI以外のプログラムの場合と同様に、GUIの場合も違いはありません。

于 2012-10-31T19:33:27.423 に答える