自从我开始用Java编程以来,每次我想创建一个GUI和更复杂的业务逻辑时,每次都会遇到同样的问题。
- 如何将 GUI 部分与逻辑部分完全分开?编辑:也许说“逻辑部分的GUI部分”略有错误。相反,更正确的是“来自侦听器部分的 GUI 部分”,因为我们不希望文件像我们编写匿名函数或内部类时那样包含大量行。
结果可能是:
public class MainFrame extends JFrame{
private final Handler handler = new Handler();
public MainFrame(){
//some code...
final JButton b = new JButton("Click Me!");
b.putClientProperty("command", "some command or a static variable from a some commands class");
b.addActionListener(this.handler);
}
}
// another class in another file
public class Handler implements ActionListener{
@Override
public void actionPerformed(ActionEvent e){
if(e.getSource() instanceof JButton){
final JButton source = (JButton)e.getSource();
if(source.getClientProperty("command").equals("some command or a static variable from a some commands class")){
//do something
}
}
}
}
如果你们中的一些人知道更好的方法,请告诉我。
当采取行动时,如何使 GUI 响应刷新?因为在上面的例子中我们写了:
b.addActionListener(this.handler);
所以只有按钮 b 知道何时执行操作。
如果我对第一个问题的解决方案对第二个问题不可靠,请为此帖子提供完整的解决方案。
我希望这对更多的人有所帮助。
谢谢。