Add space between JFrame and JPanel

How can I add space between a JFrame and JPanel inserts in this JFrame? I would enclose the space so that the elements inside the JPanel do not display too close to the JFrame

+7
source share
2 answers

Set the JPanel border using EmptyBorder with the appropriate parameters.

i.e.,

// caveat: code not tested myPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); 

If the JPanel already has a border, you can either use a compound border or wrap the JPanel in another JPanel, say using BorderLayout and at the position of BorderLayout.CENTER, and give the JPanel shell an empty border.

+11
source

Why aren't you using GridBagLayout and setBounds for components? Components will remain in the right place.

Here is an example: `

 'import javax.swing.*; import java.awt.*; public class set_Components_where_i_want { public static void main(String[] args){ JFrame frame = new JFrame(); frame.setLayout(null); //make new Components JButton b1 = new JButton("One"); JButton b2 = new JButton("Two"); JButton b3 = new JButton("Three"); //add Components first frame.add(b1); frame.add(b2); frame.add(b3); //get frame inserts Insets insets = frame.getInsets(); Dimension size = b1.getPreferredSize(); //set position here b1.setBounds(50 + insets.left, 10 + insets.top, size.width, size.height); size = b2.getPreferredSize(); b2.setBounds(110 + insets.left, 80 + insets.top, size.width, size.height); size = b3.getPreferredSize(); b3.setBounds(300 + insets.left, 60 + insets.top, size.width + 100, size.height + 40); //set size for the frame so it can contain all Components frame.setSize(600 + insets.left + insets.right, 250 + insets.top + insets.bottom); // make the frame be visible frame.setVisible(true); } 

} `

0
source

All Articles