import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /** * a GUI application demonstrating GridBagLayout * * @author Sharon Tuttle * @version 2015-10-14 */ public class GridBag0 { /** * create a GridBag0Frame * * @param args not used here */ public static void main(String[] args) { EventQueue.invokeLater( new Runnable() { public void run() { GridBag0Frame frame = new GridBag0Frame(); frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } }); } } /** * a frame with a panel using BoxLayout */ class GridBag0Frame extends JFrame { // data fields public static final int DEFAULT_WIDTH = 225; public static final int DEFAULT_HEIGHT = 150; /** * construct a GridBag0Frame instance */ public GridBag0Frame() { this.setSize(this.DEFAULT_WIDTH, this.DEFAULT_HEIGHT); this.setTitle("GridBagLayout Example 1"); GridBag0Panel panel = new GridBag0Panel(); this.add(panel); } } /** * a panel playing a little with GridBagLayout */ class GridBag0Panel extends JPanel { // data fields private final static Font DISPLAY_FONT = new Font("Dialog", Font.PLAIN, 20); // Java Tutorial warns against reusing one // GridBagContraints object for multiple // components -- BUT we are carefully doing so // here for simplicity, I hope; private GridBagConstraints constraints; /** * construct a panel using GridBagLayout */ public GridBag0Panel() { this.setLayout(new GridBagLayout()); constraints = new GridBagConstraints(); //****** // SET UP and ADD a "page start" BUTTON! // odd but true: GridBagContraints' // constraints values are public // data fields that you set // directly...! constraints.gridx = 1; constraints.gridy = 0; constraints.gridheight = 1; constraints.gridwidth = 2; constraints.weightx = 1.0; constraints.weighty = 1.0; constraints.fill = GridBagConstraints.HORIZONTAL; constraints.anchor = GridBagConstraints.LINE_START; this.add(new JButton("UP TOP!"), constraints); // gee that could be repetitive -- let's // use a helper method for the rest! this.addGB(new JButton("LEFT!"), 0, 1); this.addGB(new JButton("MIDDLE!"), 1, 1); this.addGB(new JButton("RIGHT!"), 2, 1); this.addGB(new JButton("BOTTOM!"), 1, 2); } /** * private method to JUST reset gridx and gridy * as passed, and add the passed component * subject to constraints so modified * * @param newComponent the component to be added * @param thisGridx the desired gridx for this component * @param thisGridy the desired gridy for this component */ private void addGB(Component newComponent, int thisGridx, int thisGridy) { constraints.gridx = thisGridx; constraints.gridy = thisGridy; constraints.gridwidth = 1; constraints.gridheight = 1; constraints.fill = GridBagConstraints.NONE; constraints.anchor = GridBagConstraints.PAGE_END; this.add(newComponent, constraints); } }