您需要降低這些對象之間的耦合。
你可以有一個主對象,擁有所有的文本框和按鈕(面板無關)
然後就是主對象內的separete的ActionListener(我把它稱爲調停見調解模式)
該動作偵聽器在中介器上執行一個方法,該方法又從文本字段獲取值並創建一個傳輸對象。
這樣,您減少面板,文本框等之間的耦合,並讓在一個地方(調解員),這是控制,你不要讓他們互相認識。
你可以在這個問題上的代碼來看看: https://stackoverflow.com/questions/324554/#324559
它顯示運行這些代碼的概念。
順便提一下,觀察者模式已經在JTextField,JButton,ActionListener等中實現了。您只需添加鉤子。
我希望這會有所幫助。
編輯將兩個答案合併爲一個。
這是代碼。
class App { // this is the mediator
// GUI components.
private JFrame frame;
private JTextField name;
private JTextField count;
private JTextField date;
// Result is displayed here.
private JTextArea textArea;
// Fired by this button.
private JButton go;
private ActionListener actionListener;
public App(){
actionListener = new ActionListener(){
public void actionPerformed(ActionEvent e){
okButtonPressed();
}
};
}
private void okButtonPressed(){
// template is an object irrelevant to this code.
template.setData(getData());
textArea.setText(template.getTransformedData());
}
public void initialize(){
frame = new JFrame("Code challenge v0.1");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
name = new JTextField();
count = new JTextField();
date = new JTextField();
textArea = new JTextArea();
go = new JButton("Go");
go.addActionListener(actionListener); // prepare the button.
layoutComponents(); // a lot of panels are created here. Irrelevant.
}
}
完成並運行的代碼可以檢索here:
它可能的情況下有利於組成了繼承是很重要的。