2015-02-10 75 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()並執行一些自定義設置。

相關問題