我发现,当用 Java 制作 gui 应用程序时,如果我不将 GUI 类的构造函数抽象/提取到其他类或方法来缩短它,它就会变得很长...处理大型 gui 构造函数的最佳/最合乎逻辑/最不困惑的方法是什么?我收集了两种最常用的方法来处理这个问题......什么是最好的方法,更重要的是,为什么/为什么不?
方法 1,为每个 gui 组件组织成类,其中每个类扩展其 GUI 组件:
public class GUI extends JFrame{
public GUI(String title){
super(title);
this.setVisible(true);
this.setLayout(new GridBagLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500,500);
this.add(new mainPanel());
}
private class mainPanel extends JPanel{
private mainPanel(){
this.setSize(new Dimension(500,500));
this.setLayout(new BorderLayout());
this.add(new PlayButton("Play Now"));
}
private class PlayButton extends JButton{
private PlayButton(String text){
this.setText(text);
this.setSize(150,50);
this.setBackground(Color.WHITE);
this.setForeground(Color.BLACK);
}
}
}
}
方法2:使用初始化方法,以及返回每个gui组件实例的方法:
public class GUI extends JFrame{
public GUI(String title){
super(title);
this.setVisible(true);
this.setLayout(new GridBagLayout());
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(500,500);
initGuiComponents();
}
private void initGuiComponents(){
this.add(mainPanel());
}
private JPanel mainPanel(){
JPanel mainPanel = new JPanel();
mainPanel.setSize(new Dimension(500,500));
mainPanel.setLayout(new BorderLayout());
mainPanel.add(playButton("Play Now"));
return mainPanel;
}
private JButton playButton(String text){
JButton button = new JButton();
button.setText(text);
button.setSize(150,50);
button.setBackground(Color.WHITE);
button.setForeground(Color.BLACK);
return button;
}
}
最佳答案
我认为结合使用两者是一个好主意。
不使用内部类,使用顶级类可能会使代码更易于维护。您可以根据功能和职责将框架划分为小面板。如果您的隔离足够好,它们将是松散耦合的,您不需要向它们传递许多参数。
同时,如果构造函数或任何方法增长得不成比例,将紧密相关的操作合并到私有(private)方法中可能有助于提高代码的可读性。
<小时/>美丽的程序源于高质量的抽象和封装。
尽管实现这些需要实践和经验,但坚持 SOLID principles应该始终是您的首要任务。
希望这有帮助。
祝你好运。
关于Java - 处理大型 GUI 构造函数的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28437817/