Source code: com/arranger/jarl/test/GridBagTest.java
1 package com.arranger.jarl.test;
2
3 import java.awt.*;
4 import java.awt.event.*;
5 import javax.swing.*;
6
7 public class GridBagTest extends JFrame {
8 boolean inAnApplet = true;
9 final boolean shouldFill = true;
10 final boolean shouldWeightX = true;
11
12 public GridBagTest() {
13 JButton button;
14 Container contentPane = getContentPane();
15 GridBagLayout gridbag = new GridBagLayout();
16 GridBagConstraints c = new GridBagConstraints();
17 contentPane.setLayout(gridbag);
18 if (shouldFill) {
19 //natural height, maximum width
20 c.fill = GridBagConstraints.HORIZONTAL;
21 }
22
23 // button = new JButton("Button 1");
24 JTextField textField = new JTextField("this is a test");
25 if (shouldWeightX) {
26 c.weightx = 0.5;
27 }
28 c.gridx = 0;
29 c.gridy = 0;
30 gridbag.setConstraints(textField, c);
31 contentPane.add(textField);
32
33 button = new JButton("2");
34 c.gridx = 1;
35 c.gridy = 0;
36 gridbag.setConstraints(button, c);
37 contentPane.add(button);
38
39 button = new JButton("Button 3");
40 c.gridx = 2;
41 c.gridy = 0;
42 gridbag.setConstraints(button, c);
43 contentPane.add(button);
44
45 button = new JButton("Long-Named Button 4");
46 c.ipady = 40; //make this component tall
47 c.weightx = 0.0;
48 c.gridwidth = 3;
49 c.gridx = 0;
50 c.gridy = 1;
51 gridbag.setConstraints(button, c);
52 contentPane.add(button);
53
54 button = new JButton("Button 5");
55 c.ipady = 0; //reset to default
56 c.weighty = 1.0; //request any extra vertical space
57 c.anchor = GridBagConstraints.SOUTH; //bottom of space
58 c.insets = new Insets(10,0,0,0); //top padding
59 c.gridx = 1; //aligned with button 2
60 c.gridwidth = 2; //2 columns wide
61 c.gridy = 2; //third row
62 gridbag.setConstraints(button, c);
63 contentPane.add(button);
64
65 addWindowListener(new WindowAdapter() {
66 public void windowClosing(WindowEvent e) {
67 if (inAnApplet) {
68 dispose();
69 } else {
70 System.exit(0);
71 }
72 }
73 });
74 }
75
76 public static void main(String args[]) {
77 GridBagTest window = new GridBagTest();
78 window.inAnApplet = false;
79
80 window.setTitle("GridBagLayout");
81 window.pack();
82 window.setVisible(true);
83 }
84 }