2012-11-20 53 views
1

我必須使用網格包佈局來設計JFrame中的按鈕。因此所有系統的定位可能都是相同的。我使用下面的代碼,但我想分組按鈕。
我想要設計按鈕,以便可以創建三個組,每組4個按鈕。使用網格包佈局來設計java框架

import java.awt.GridLayout; 

    import javax.swing.JButton; 
    import javax.swing.JFrame; 

    public class GridLayoutTest { 

    public static void main(String[] args) { 
    JFrame.setDefaultLookAndFeelDecorated(true); 
    JFrame frame = new JFrame("GridLayout Test"); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.setLayout(new GridLayout(3, 2)); 
    frame.add(new JButton("Button 1")); 
    frame.add(new JButton("Button 2")); 
    frame.add(new JButton("Button 3")); 
    frame.add(new JButton("Button 4")); 
    frame.add(new JButton("Button 5")); 
    frame.add(new JButton("Button 6")); 
    frame.add(new JButton("Button 7")); 
    frame.add(new JButton("Button 8")); 
    frame.pack(); 
    frame.setVisible(true); 
    } 
    } 
+2

你的標題說的GridBagLayout,但你的代碼使用網格佈局。他們是非常不同的東西。你在問什麼? –

+2

爲什麼*必須*您使用GridBagLayout並且只使用GridBagLayout?爲什麼不嵌套每個使用自己的佈局管理器的JPanel? –

+0

*「我想設計按鈕,以便可以創建三個組,每組4個按鈕」*以及組應如何佈置?水平地並排,在一個圓圈或三角形中? – MadProgrammer

回答

5

所以,像...

enter image description here

public class BadLayout04 { 

    public static void main(String[] args) { 
     new BadLayout04(); 
    } 

    public BadLayout04() { 
     EventQueue.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       try { 
        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); 
       } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { 
       } 

       JFrame frame = new JFrame(); 
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
       frame.setLayout(new BorderLayout()); 
       frame.add(new ButtonsPane()); 
       frame.pack(); 
       frame.setLocationRelativeTo(null); 
       frame.setVisible(true); 
      } 
     }); 
    } 

    public class ButtonsPane extends JPanel { 

     public ButtonsPane() { 

      JPanel group1 = createGroup(1); 
      JPanel group2 = createGroup(5); 
      JPanel group3 = createGroup(9); 

      setLayout(new GridBagLayout()); 
      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.gridx = 0; 
      gbc.gridy = 0; 
      add(group1, gbc); 
      gbc.gridx = 1; 
      add(group2, gbc); 
      gbc.gridx = 0; 
      gbc.gridy++; 
      gbc.gridwidth = GridBagConstraints.REMAINDER; 
      add(group3, gbc); 

     } 

     public JPanel createGroup(int index) { 

      JPanel group = new JPanel(new GridBagLayout()); 
      group.setBorder(new EmptyBorder(4, 4, 4, 4)); 
      GridBagConstraints gbc = new GridBagConstraints(); 
      gbc.fill = GridBagConstraints.BOTH; 
      for (int loop = 0; loop < 4; loop++) { 
       group.add(new JButton("Button " + (index++)), gbc); 
      } 

      return group; 

     } 

    } 

} 
+0

雅肯定,並感謝很多現在我會根據我的要求定製它 – adesh

+0

你沒有回答我的jeditorpane問題 – adesh

+0

什麼jeditorpane問題? – MadProgrammer