- Swing Programming Examples
- Example - Home
- Example - Environment Setup
- Example - Borders
- Example - Buttons
- Example - CheckBoxes
- Example - Combo Boxes
- Example - Color Choosers
- Example - Dialogs
- Example - Editor Panes
- Example - File Choosers
- Example - Formatted TextFields
- Example - Frames
- Example - Lists
- Example - Layouts
- Example - Menus
- Example - Password Fields
- Example - Progress Bars
- Example - Scroll Panes
- Example - Sliders
- Example - Spinners
- Example - Tables
- Example - Toolbars
- Example - Tree
- Swing Useful Resources
- Swing - Quick Guide
- Swing - Useful Resources
- Swing - Discussion
Swing Examples - Grid Bag Layout
This is the most flexible layout manager class. The object of GridBagLayout aligns the component vertically, horizontally, or along their baseline without requiring the components of the same size.
Example
import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class SwingTester { public static void main(String[] args) { createWindow(); } private static void createWindow() { JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); } private static void createUI(final JFrame frame){ JPanel panel = new JPanel(); GridBagLayout layout = new GridBagLayout(); panel.setLayout(layout); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy = 0; panel.add(new JButton("Button 1"),gbc); gbc.gridx = 1; gbc.gridy = 0; panel.add(new JButton("Button 2"),gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.ipady = 20; gbc.gridx = 0; gbc.gridy = 1; panel.add(new JButton("Button 3"),gbc); gbc.gridx = 1; gbc.gridy = 1; panel.add(new JButton("Button 4"),gbc); gbc.gridx = 0; gbc.gridy = 2; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 2; panel.add(new JButton("Button 5"),gbc); frame.getContentPane().add(panel, BorderLayout.CENTER); } }
Output
swingexamples_layouts.htm
Advertisements
To Continue Learning Please Login
Login with Google