package examples; import java.awt.*; import javax.swing.*; import static java.awt.BorderLayout.*; public class GUI extends JPanel { JButton button; JSlider slider; JCheckBox box; JTextArea text; static final GridBagConstraints gbc = new GridBagConstraints(); static enum LayoutChoice {flow, border, grid, gridbag}; public GUI(LayoutChoice lc) { createComponents(); switch (lc) { case flow: addComponentsFlow(); break; case border: addComponentsBorder(); break; case grid: addComponentsGrid(); break; case gridbag: addComponentsGridBag(); } } void createComponents() { button = new JButton("press me"); slider = new JSlider(); box = new JCheckBox("useless option"); text = new JTextArea("abc def"); } void addComponentsFlow() { setLayout(new FlowLayout()); add(button); add(slider); add(box); add(new JScrollPane(text)); } void addComponentsGrid() { setLayout(new GridLayout(2,2)); add(button); add(slider); add(box); add(new JScrollPane(text)); } void addComponentsBorder() { setLayout(new BorderLayout()); add(button,WEST); add(slider,SOUTH); add(box,NORTH); add(new JScrollPane(text),CENTER); } void addComponentsGridBag() { setLayout(new GridBagLayout()); add(button,0,0,1,2); add(slider,0,3,2,1); add(box,1,0,2,1); JScrollPane jsp = new JScrollPane(text); jsp.setPreferredSize(new Dimension(300,100)); add(jsp,0,5,2,2); GUI g = new GUI(LayoutChoice.border); g.setPreferredSize(new Dimension(300,200)); add(g,0,7,2,3); } void add(JComponent c, int x, int y, int width, int height) { gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = width; gbc.gridheight = height; gbc.anchor = GridBagConstraints.EAST; add(c, gbc); } public static void main(String[] args) { GUI g = new GUI(LayoutChoice.gridbag); JFrame f = new JFrame("My GUI"); f.getContentPane().add(g); f.pack(); f.setVisible(true); } }