2015-02-10 70 views
1

我发现,当在Java中制作gui应用程序时,如果我不抽象/提取它到其他类或方法以缩短它,那么我的GUI类的构造函数会变得非常长...什么是最好的/最合理的/最不混乱的处理大型gui构造函数的方法?我收集了我用来处理这个问题的两种最常用的方法......最好的方法是什么,更重要的是,为什么/为什么不呢?Java - 处理大型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; 
    } 
} 

回答

0

我认为使用两者的组合将是一个好主意。

而不是使用内部类,具有顶级类可能会使代码更易于维护。您可以根据功能和责任将框架分成小面板。如果你的隔离足够好,他们会松散耦合,你不需要传递很多参数给他们。与此同时,如果构造函数或任何方法的比例不断增长,那么将紧密相关的操作转化为私有方法可能有助于使代码可读。


美丽的程序来自高质量的抽象和封装。

尽管实现这些需求的实践和经验,坚持SOLID principles应始终是您的第一要务。

希望这会有所帮助。
祝你好运。

0

如果您在许多部件(即每个按钮具有相同的BG/FG色)使用相同的设置,使用工厂:

class ComponentFactory{ 
    static JButton createButton(String text) { 
     JButton button = new JButton(); 
     button.setBackground(Color.WHITE); 
     button.setForeground(Color.BLACK); 
    } 
} 

然后,在你的构造函数,可以调节非恒定设置:

JButton button = ComponentFactory.createButton(); 
button.setText(text); 
[...] 

这样做的好处是您只需更改一次设置(如BG颜色)一次即可更改所有按钮的外观。

为了保持施工人员的简洁,我通常会将流程拆分为createChildren()layoutComponents()registerListeners()以及其他任何看起来有用的东西。然后我从抽象超类的构造函数中调用这些方法。因此,许多子类根本不需要构造函数 - 或者是一个非常短的函数,它会调用super()并执行一些自定义设置。

相关问题