[英]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.