:
또한 JTextField로의 유용에 대한 리스너에이 링크를 발견했다.
당신은 마스터 개체를 가질 수있다, 즉 모든 텍스트 필드와 버튼 (패널은 무관) 소유
그런 다음 마스터 객체 내에서의 separete의 ActionListener를 (내가 중재자 중재자 패턴을 참조 호출)
액션 리스너는 중재자에게 텍스트 필드의 값을 가져 와서 전송 객체를 생성하는 메소드를 수행합니다.
이렇게하면 패널, 텍스트 필드 등의 결합을 줄이고 컨트롤을 한 곳 (중재자)에서 제어 할 수 있습니다. 즉, 서로 알릴 수 없습니다.
는이 문제의 코드를 좀 걸릴 수 있습니다 : 그것은 코드를 실행에 이러한 개념을 보여줍니다 https://stackoverflow.com/questions/324554/#324559
.
BTW 관찰자 패턴은 이미 JTextField, JButton, ActionListener 등에 구현되어 있습니다. 후크를 추가하면됩니다.
이 정보가 도움이되기를 바랍니다.
수정 2 개의 답변을 하나로 합쳤습니다.
이것은 코드입니다.
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:
검색 할 수 있습니다 가능하면 상속을 통해 구성을 선호하는 것이 중요하다.