2012-01-12 21 views
1

自分の別のクラスにある自分の電卓から他のクラスのJTextPaneに値を取得しようとしています。私の唯一の懸念は、自分のプログラムの設計のために私がそうすることができないということです。あるクラスから別のクラスに値を渡す

私のメインクラスには、JMenuItemがクリックされたときに別のフレームを開く内部クラスがあります。


public class Notepad extends JFrame 
{ 
    ... 
    // Opens when the user clicks Calculator 
    // (JMenuItem in the JFrame of the Notepad class) 
    private class Calculator implements ActionListener 
    { 
     public void actionPerformed(ActionEvent event) 
     { 
      Calculate c = new Calculate(); 
      c.buildGUI(); 

      // I've tried creating a reference to the Insert class and tried to 
      // retrieve the value from the JLabel in the Calculator but continuously 
      // receive a NullPointerException 
     } 
    } 
    ... 
} 

そして、私の他のクラスで私は(彼らが望むなら、ユーザはJTextPaneに自分の答えを挿入することができます)[挿入]ボタンのための内部クラスを持っています。

***メモ帳のクラスに値を渡しても、私のプログラムの設定によっては動作しないことを発見した "ゲッター"と "セッター"を作成するなど、 。


public class Calculate extends JFrame 
{ 
    ... 
    /* Insert 
    * Inserts the answer into the 
    * text pane of the Notepad class 
    */ 
    private class Insert implements ActionListener 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      String answer = proposal.getText(); // from the JLabel 
      if (answer.isEmpty()) JOptionPane.showMessageDialog(frame, "Enter two numbers and hit the desired operator, please"); 
      // else, insert the answer 
      // *** 
     } 
    } 
    ... 
} 

私の問題のもう一つは、私のメモ帳のためのフレーム内JMenuItem(電卓)がクリックされたときのためにJLabel(回答に値がないので、私はNullPointerExceptionを受けるということです電卓)。

したがって、JLabelの値を電卓から取得して、[挿入]をクリックしたときにメモ帳フレームのJTextPaneに挿入するにはどうすればよいですか?また、私のプログラムがそのようなアクションを実行するようにセットアップされていない場合、再設計提案はありますか?

答えて

3

最も簡単な方法は、NotePadへの参照をCalculatorクラスに渡すことです。

public class Calculator extends JFrame{ 

     Notepad notepad; 

     public Caluclator(Notepad np){ 
      this(); 
      notepad = np; 
      //any other code you need in your constructor 
     } 

     ... 

     private class Insert implements ActionListener 
     { 
      public void actionPerformed(ActionEvent e) 
      { 
       String answer = proposal.getText(); // from the JLabel 
       if (answer.isEmpty()) JOptionPane.showMessageDialog(frame, "Enter two numbers and hit the desired operator, please"); 
       else{ 
        notepad.myJTextPane.setText(answer); 
       } 
      // *** 
     } 


} 

メモ帳クラスでそれを呼び出すために:電卓クラスは、このようになります、のようないくつかのデザインパターンを検索することをお勧めだろう、と述べた

Calculate c = new Calculate(Notepad.this); 

Observerは、別のクラスが変更されたときにあるクラスを正確に更新するためのものです。

+1

コードはコンパイルされず、命名規則に違反しているので、この回答を書くのは急いでいると思います。変数 'np'は' Calculator'コンストラクタに対してローカルです。ですから、私が言っていることは、 '> np。** myJTextPane ** .setText(answer);' 'notepad。** myJTextPane ** .setText(answer);'それ以外のnice答え! +1 – fireshadow52

+0

ああ、....ありがとう@ fireshadow52 –

+0

お手伝いします。 :) – fireshadow52

関連する問題