import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class Example1 extends JFrame { public Example1() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Example 1"); // create a panel with a GridBagLayout manager JPanel panel = new JPanel(new GridBagLayout()); // create a button and set its ipadx property JButton button = new JButton("Button"); GridBagConstraints gbc = new GridBagConstraints(); gbc.ipadx = 20; panel.add(button, gbc); // add the panel to the frame getContentPane().add(panel); pack(); setVisible(true); } public static void main(String[] args) { new Example1(); } }
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; public class Example2 extends JFrame { public Example2() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setTitle("Example 2"); // create a panel with a GridBagLayout manager JPanel panel = new JPanel(new GridBagLayout()); // create a text field and set its ipadx property JTextField textField = new JTextField("Text field"); GridBagConstraints gbc = new GridBagConstraints(); gbc.ipadx = 50; panel.add(textField, gbc); // create a button and set its ipadx property JButton button = new JButton("Button"); gbc = new GridBagConstraints(); gbc.gridx = 1; gbc.ipadx = 20; panel.add(button, gbc); // add the panel to the frame getContentPane().add(panel); pack(); setVisible(true); } public static void main(String[] args) { new Example2(); } }This example creates a JTextField and sets its ipadx property to 50, and also creates a JButton with an ipadx property of 20. The two components are added to the same panel, but because they have different ipadx values, they will have different amounts of padding along the x-axis.