使用网格包布局来设计java框架

时间:2012-11-20 04:58:44

标签: java swing awt grid-layout gridbaglayout

我必须使用网格包布局在JFrame中设计按钮。这样所有系统的定位都可以相同。我使用以下代码,但我想分组按钮 我想设计按钮,这样就可以创建三组,每组有4个按钮。

   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);
   }
  }

1 个答案:

答案 0 :(得分: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;

        }

    }

}