COMP2396
Loading...
Searching...
No Matches
GridBagLayoutEx.java
Go to the documentation of this file.
1import javax.swing.*;
2import java.awt.*;
3
4public class GridBagLayoutEx {
5 public static void main(String[] args) {
7 gui.go();
8 }
9
10 public void go() {
11 JFrame frame = new JFrame();
12 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13 JPanel panel = new JPanel();
14 panel.setLayout(new GridBagLayout());
15 GridBagConstraints c = new GridBagConstraints();
16 c.gridx = 0;
17 c.gridy = 0;
18 c.gridwidth = 1; // default value
19 c.gridheight = 1; // default value
20 c.weightx = 0.0; // default value
21 c.weighty = 0.0; // default value
22 c.anchor = GridBagConstraints.CENTER; // default value
23 c.fill = GridBagConstraints.HORIZONTAL;
24 c.insets = new Insets(0, 0, 0, 0); // default value
25 c.ipadx = 0; // default value
26 c.ipady = 0; // default value
27 JButton button = new JButton("Button 1");
28 c.weightx = 0.5;
29 panel.add(button, c);
30 button = new JButton("Button 2");
31 c.gridx = 1; // 2nd column
32 panel.add(button, c);
33 button = new JButton("Button 3");
34 c.gridx = 2; // 3rd column
35 panel.add(button, c);
36 button = new JButton("Button 4");
37 c.gridx = 0; // 1st column
38 c.gridy = 1; // 2nd row
39 c.gridwidth = 3; // spans 3 columns
40 c.weightx = 0.0;
41 c.ipady = 40; // makes the button tall
42 panel.add(button, c);
43 button = new JButton("Button 5");
44 c.gridx = 1; // 2nd column
45 c.gridy = 2; // 3rd row
46 c.gridwidth = 2; // spans 2 columns
47 c.weighty = 1.0; // takes up extra vertical space
48 c.anchor = GridBagConstraints.SOUTH;
49 c.insets = new Insets(10, 0, 0, 0); // top padding
50 c.ipady = 0;
51 panel.add(button, c);
52 frame.add(panel);
53 frame.pack();
54 frame.setVisible(true);
55 }
56}
static void main(String[] args)