2013-05-05 121 views
-7

我想用Java創建一個用戶界面(下圖)。我已經使用了網格佈局,但我如何平分?如何在Java中使用Swing創建用戶界面?

Enter image description here

+5

*請給一些代碼*。我們不是代碼寫作服務。 – christopher 2013-05-05 12:20:56

+1

嘗試使用GridBagLayout ..閱讀關於gridwidth和gridheight。基本上我的意思是說,你可以將整個用戶界面劃分爲9行和12列......只是爲了讓你理解,使第一個網格,即x = 0,y = 0(我看到時間 - 08:58: 10),網格寬度爲4 ..同樣 – Mady 2013-05-05 12:23:20

+0

@Mady:給我參考鏈接 – 2013-05-05 12:24:36

回答

4

這裏是你的代碼

public class SwingSolution extends JFrame 
{ 
    private JPanel componentPanel = null; 
    private JButton buttonWithWidth2 = null;  
    private JButton button2 = null; 
    private JButton buttonWithHeight2 = null; 
    private JButton button4 = null; 
    private JButton button5 = null; 

    public JPanel getComponentPanel() 
    { 
     if(null == componentPanel) 
     { 
      componentPanel = new JPanel(); 
      GridBagLayout gridBagLayout = new GridBagLayout(); 
      componentPanel.setLayout(gridBagLayout); 

      GridBagConstraints constraint = new GridBagConstraints(); 

      constraint.gridx = 0; 
      constraint.gridy = 0; 
      // Set gridwidth to 2 grids 
      constraint.gridwidth = 2; 
      buttonWithWidth2 = new JButton("Button Width 2"); 
      componentPanel.add(buttonWithWidth2, constraint); 

      constraint.gridx = 2; 
      constraint.gridy = 0; 
      // set the gridwidth back to normal i.e. 1 grid 
      constraint.gridwidth = 1; 
      button2 = new JButton("Button 2"); 
      componentPanel.add(button2, constraint); 

      constraint.gridx = 0; 
      constraint.gridy = 1; 
      // set the gridheight to 2 
      constraint.gridheight = 2; 
      buttonWithHeight2 = new JButton("Button Height 2"); 
      componentPanel.add(buttonWithHeight2, constraint); 

      constraint.gridx = 1; 
      constraint.gridy = 1; 
      // set the gridheight back to normal i.e. 1 grid 
      constraint.gridheight = 1; 
      button4 = new JButton("Button 4"); 
      componentPanel.add(button4, constraint); 

      constraint.gridx = 1; 
      constraint.gridy = 2; 
      button5 = new JButton("Button 5"); 
      componentPanel.add(button5, constraint); 
     } 

     return componentPanel; 
    } 

    public static void main(String[] args) 
    { 
     JFrame frame = new JFrame(); 
     SwingSolution main = new SwingSolution(); 

     frame.setTitle("Simple example"); 
     frame.setSize(300, 200); 
     frame.setLocationRelativeTo(null); 

     frame.setContentPane(main.getComponentPanel()); 

     frame.setVisible(true); 
     frame.setDefaultCloseOperation(EXIT_ON_CLOSE); 
    } 
} 

它應該給你輸出:

Output

Output with grid marking

+0

提前致謝。現在我明白了GridBagLayout。 – 2013-05-05 13:06:19

相關問題