1

jFrame が 1 つあり、jTextbox とボタンが 1 つあります。別の jFrame には、単一の jLabel があります。ボタンが押されたときに、最初のフレームのテキストボックスに書かれたテキストを2番目のフレームのjLabelに引き出したいです。そして、これについて検索したところ、信頼できない回答がいくつか得られました。しかし、私の知る限り、別の静的クラスを作成するか、この参照を呼び出すことで実行できます。

4

2 に答える 2

8

「どのように」を推進するのは、「何を」達成したいかという問題です...

例えば...

最初のフレーム内の 2 番目のフレームへの参照を維持し、ボタンがクリックされたときに、2 番目のフレームに変更が発生したことを伝えることができます...

public class FirstFrame extends JFrame {
    // Reference to the second frame...
    // You will need to ensure that this is assigned correctly...
    private SecondFrame secondFrame;
    // The text field...
    private JTextField textField;

    /*...*/

    // The action handler for the button...
    public class ButtonActionHandler implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            secondFrame.setLabelText(textField.getText());
        }
    }
}

これに関する問題は、最初に を公開しSecondFrame、たとえばすべてのコンポーネントを削除するなど、厄介なことを実行できることです。

より良い解決策は、2 つのクラスが互いに通信できるようにする一連のインターフェイスを提供することです...

public interface TextWrangler {
    public void addActionListener(ActionListener listener);
    public void removeActionListener(ActionListener listener);
    public String getText();
}

public class FirstFrame extends JFrame implements TextWrangler {
    private JButton textButton;
    private JTextField textField;

    /*...*/

    public void addActionListener(ActionListener listener) {
        textButton.addActionListener(listener);
    }

    public void removeActionListener(ActionListener listener) {
        textButton.removeActionListener(listener);
    }

    public String getText() {
        return textField.getText();
    }
}

public class SecondFrame extends JFrame {
    private JLabel textLabel;
    private JTextField textField;
    private TextWrangler textWrangler;

    public SecondFrame(TextWrangler wrangler) {
        textWrangler = wrangler;
        wrangler.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                textLabel.setText(textWrangler.getText());
            }
        });
        /*...*/
    }
}

これは基本的に、SecondFrameが実際にアクセスできるものを制限します。はソースを使用してより多くの情報を見つけることができると主張することがActionListenerできますが、それがどのように実装されるべきかについて言及していないため、その性質上、信頼できないメカニズムになります...SecondFrameActionEventinterface

これはObserver パターンの基本的な例です

于 2013-09-03T00:09:37.777 に答える