[英]Where to put action listeners?
對於小型 Swing 應用程序中ActionListener
實例的最佳類在哪里,我有點困惑。
如果我有一個Controller
,一個MainFrame
用於主JFrame
和各種JPanel
容器,例如LeftPanel
、 RightPanel
等,每個容器都有按鈕、列表等。
放置動作監聽器的最佳位置在哪里? 我應該將它們與組件放在同一個類中(作為內部類或實現動作偵聽器的類),在MainFrame
中,因為這是所有面板的“父級”,還是在Controller
中,它實際上只有main()
方法和其他一些 Swing 細節?
每種方法似乎都有其優點和缺點。 我正在嘗試將功能與功能分離,但我發現很難解決這個問題。
還是我錯過了另一種(更好的)方式?
面板相互通信的一種可能方式是通過主機架。 每個面板都會有一個對主框架的引用,主框架提供所有操作,例如從表單讀取數據,更新數據到表單。 下面是一個例子:
class UserForm extends JPanel {
private final MyApp app;
private final JTextField userNameField = new JTextField(20);
public UserForm(MyApp app){
this.app = app;
this.add(userNameField);
}
public String getUserName(){
return userNameField.getText();
}
public void setUserName(String name){
userNameField.setText(name);
}
}
class FormControl extends JPanel {
private final MyApp app;
private final JButton randNameButton = new JButton("Random");
private final JButton saveButton = new JButton("Save");
private final String[] names = {"john", "mike", "bill", "joe"};
private final Random r = new Random();
public FormControl(MyApp app){
this.app = app;
this.setLayout(new FlowLayout());
this.add(randNameButton);
this.add(saveButton);
randNameButton.addActionListener(e->app.setUserName(names[r.nextInt(4)]));
saveButton.addActionListener(e->app.save());
}
}
public class MyApp extends JFrame{
private final UserForm form = new UserForm(this);
private final FormControl control = new FormControl(this);
public MyApp(){
this.setTitle("Demo");
this.setSize(200, 100);
JPanel pane = new JPanel();
pane.setSize(200,100);
pane.setLayout(new BorderLayout());
pane.add(form, BorderLayout.NORTH);
pane.add(control, BorderLayout.SOUTH);
this.setContentPane(pane);
}
// all the operations are here.
public String getUserName(){
return form.getUserName();
}
public void setUserName(String userName){
form.setUserName(userName);
}
public void save(){
System.out.println("Saving");
System.out.println(getUserName());
System.out.println("Done saving.");
}
public static void main(String[] args) {
new MyApp().setVisible(true);
}
}
我會使用 lambda 作為動作監聽器。 請參見下面的示例:
public class JavaApplication7 extends JFrame{
public JavaApplication7(){
this.setTitle("Demo");
this.setSize(100, 100);
JButton b = new JButton("Click");
b.addActionListener(e->{
System.out.println("hello");
System.out.println("from " + this.getTitle());
});
this.setContentPane(b);
}
public static void main(String[] args) {
new JavaApplication7().setVisible(true);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.