我发现,当在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;
}
}