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
|
package swing.layout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
public class GridBagTestForm extends JPanel {
private List<JPanel> panels;
private Color[] borderColors = { Color.blue, Color.yellow, Color.green, Color.red, Color.black, Color.orange };
private int[] panelHeights = { 10, 45, 20, 35, 60, 15, 30 };
public GridBagTestForm() {
panels = new ArrayList<JPanel>();
init();
}
private GridBagConstraints createConstraints() {
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1.0f;
c.anchor = GridBagConstraints.NORTH;
return c;
}
private GridBagConstraints createFillConstraints() {
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
c.fill = GridBagConstraints.BOTH;
c.weightx = 1.0f;
c.weighty = 1.0f;
c.anchor = GridBagConstraints.NORTH;
return c;
}
private void init() {
this.setLayout(new GridBagLayout());
this.setBackground(Color.CYAN);
GridBagConstraints c = createConstraints();
for (int i = 0; i < 40; i++) {
JPanel p = new JPanel();
p.setBackground(borderColors[i % borderColors.length]);
p.setPreferredSize(new Dimension(0, panelHeights[i % panelHeights.length]));
this.add(p, c);
}
JPanel filler = new JPanel();
filler.setOpaque(false);
filler.setPreferredSize(new Dimension(0,0));
filler.setMinimumSize(new Dimension(0,0));
this.add(filler, createFillConstraints());
}
public static void main(String[] args) {
GridBagTestForm gbtf = new GridBagTestForm();
JFrame f = new JFrame();
f.add(new JScrollPane(gbtf));
f.pack();
f.setLocationRelativeTo(null);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
f.setVisible(true);
}
} |
Partager