-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathGridBagDemo2.java
88 lines (69 loc) · 2.73 KB
/
GridBagDemo2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Fig. 14.20: GridBagDemo2.java
// Demonstrating GridBagLayout constants.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main extends JFrame {
private GridBagLayout layout;
private GridBagConstraints constraints;
private Container container;
// set up GUI
public Main(){
super( "GridBagLayout");
container = getContentPane();
layout = new GridBagLayout();
container.setLayout( layout );
// instantiate gridbag constraint
constraints = new GridBagConstraints();
// create GUI components
String metals[] = { "Copper", "Aluminum", "Silver"};
JComboBox comboBox = new JComboBox( metals );
JTextField textField = new JTextField( "TextField");
String fonts[] = { "Serif", "Monospaced"};
JList list = new JList( fonts );
String names[] = { "zero", "one", "two", "three", "four"};
JButton buttons[] = new JButton[ names.length ];
for( int count = 0; count < buttons.length; count++ )
buttons[ count ] = new JButton( names[ count ] );
// define GUI component constraints for textField
constraints.weightx = 1;
constraints.weighty = 1;
constraints.fill = GridBagConstraints.BOTH;
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent( textField );
// buttons[0] --weightx and weighty are 1: fill is BOTH
constraints.gridwidth = 1;
addComponent( buttons[ 0] );
// buttons[1] --weightx and weighty are 1: fill is BOTH
constraints.gridwidth = GridBagConstraints.RELATIVE;
addComponent( buttons[ 1] );
// buttons[2] --weightx and weighty are 1: fill is BOTH
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent( buttons[ 2] );
// comboBox --weightx is 1: fill is BOTH
constraints.weighty = 0;
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent( comboBox );
// buttons[3] --weightx is 1: fill is BOTH
constraints.weighty = 1;
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent( buttons[ 3] );
// buttons[4] --weightx and weighty are 1: fill is BOTH
constraints.gridwidth = GridBagConstraints.RELATIVE;
addComponent( buttons[ 4] );
// list --weightx and weighty are 1: fill is BOTH
constraints.gridwidth = GridBagConstraints.REMAINDER;
addComponent( list );
setSize( 300, 200);
setVisible( true);
} // end constructor
// add a Component to the container
private void addComponent( Component component ){
layout.setConstraints( component, constraints );
container.add( component ); // add component
}
public static void main( String args[] ) {
Main application = new Main();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE);
}
} // end class GridBagDemo2