Java examples for Swing:Layout Manager
Add a component to a container with a GridBagLayout, creating GridBagConstraints for it.
//package com.java2s; import java.awt.AWTException; import java.awt.Component; import java.awt.Container; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.LayoutManager; public class Main { /**/* www .ja va 2s . c om*/ * Add a component to a container with a GridBagLayout, creating * GridBagConstraints for it. * * @param container * @param component * @param gridX * @param gridY * @param gridWidth * @param gridHeight * @param fill * @param anchor * @throws java.awt.AWTException */ public static void addGridBagComponent(Container container, Component component, int gridX, int gridY, int gridWidth, int gridHeight, int fill, int anchor) throws AWTException { addGridBagComponent(container, component, gridX, gridY, gridWidth, gridHeight, fill, anchor, new Insets(0, 0, 0, 0)); } public static void addGridBagComponent(Container container, Component component, int gridX, int gridY, int gridWidth, int gridHeight, int fill, int anchor, Insets insets) throws AWTException { LayoutManager lm = container.getLayout(); if (!(lm instanceof GridBagLayout)) { throw new AWTException("Invalid layout: " + lm); } else { GridBagConstraints gbc = getGridBagConstraints(gridX, gridY, gridWidth, gridHeight, fill, anchor); gbc.insets = insets; ((GridBagLayout) lm).setConstraints(component, gbc); container.add(component); } } public static GridBagConstraints getGridBagConstraints(int gridX, int gridY, int gridWidth, int gridHeight, int fill, int anchor) { GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = gridX; gbc.gridy = gridY; gbc.gridwidth = gridWidth; gbc.gridheight = gridHeight; gbc.fill = fill; gbc.anchor = anchor; return gbc; } }