使用静态类或此引用将数据从一个Jframe传输到另一个jframe?

Ron*_*shi 1 java swing

我有一个jFrame,它有一个jTextbox和一个按钮.另一个jFrame有一个jLabel.我想在按下按钮时将第一帧文本框中写入的文本显示到第二帧的jLabel.正如我搜索到的那样,我得到了一些不可靠的答案.但据我所知,可以通过创建另一个静态类或通过调用此引用来完成.

Mad*_*mer 7

这是一个"你想要实现什么"的问题,将推动"如何"......

例如...

您可以在第一帧内保持对第二帧的引用,并在单击该按钮时,告诉第二帧发生了更改...

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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这个问题是它暴露SecondFrame给第一个,允许它做一些讨厌的事情,比如删除所有的组件.

一个更好的解决方案是提供一系列接口,允许两个类相互通信......

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());
            }
        });
        /*...*/
    }
}
Run Code Online (Sandbox Code Playgroud)

这基本上限制了SecondFrame实际可以访问的内容.尽管可以认为,ActionListenerSecondFrame可以使用ActionEvent源,以了解更多的信息,通过它的性质,这将是一个不可靠的机制,因为interface没有提到它应该如何实现?

这是观察者模式的基本示例