我有一个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
可以实际获得。 虽然可以说 ActionListener
在 SecondFrame
可以使用 ActionEvent
源来查找更多的信息,就其本质而言,这将是一个不可靠的机制,因为它是一个不可靠的机制。interface
没有提到应该如何实施......
这是一个基本的例子。观察者模式