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

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

这是一个“想要实现什么”的问题,将推动“如何”……

例如…

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

 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暴露给第一个,允许它对它做一些令人讨厌的事情,例如删除所有组件。

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

 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实际可以访问的内容。 虽然可以说SecondFrame中的ActionListener可以使用ActionEvent源来查找更多信息,但就其本质而言,它将是一个不可靠的机制,因为interface没有提到它应该如何实现……

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