If I add components like JButton
s on the East or West side, how do I prevent it from hugging the side of the screen? I want some space between the JButton
s and the edge of the screen.
Class BorderLayout. A border layout lays out a container, arranging and resizing its components to fit in five regions: north, south, east, west, and center.
Each region can contain only one component and is identified by a corresponding constant as NORTH, SOUTH, EAST, WEST, and CENTER. Constructors: BorderLayout(): It will construct a new borderlayout with no gaps between the components.
JPanel panel = new JPanel(); panel. SetLayout(new BorderLayout(100,100)); panel. add(pic1,BorderLayout. CENTER); panel.
call setBorder
on your JButton like this:
setBorder( new EmptyBorder( 3, 3, 3, 3 ) )
From the JavaDoc, an EmptyBorder is a "transparent border which takes up space but does no drawing". In my example it shall take 3 pixels respectively top, left, bottom and right.
Complete code whose purpose is only to show how to use EmptyBorder:
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.EmptyBorder;
public class ALineBorder {
public static void main(String args[]) {
JFrame frame = new JFrame("Line Borders");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton button1 = new JButton("Button1");
button1.setBorder( new EmptyBorder( 8, 8, 8, 8 ) );
JButton button2 = new JButton("Button2");
JButton button3 = new JButton("Button3");
button3.setBorder( new EmptyBorder( 16, 16, 16, 16 ) );
Container contentPane = frame.getContentPane();
contentPane.add(button1, BorderLayout.WEST);
contentPane.add(button2, BorderLayout.CENTER);
contentPane.add(button3, BorderLayout.EAST);
frame.pack();
frame.setSize(300, frame.getHeight());
frame.setVisible(true);
}
}
Most likely you have (or soon will have) more than one button in the container, and want to align them horizontally. So consider putting the buttons within in a nested JPanel
with a GridBagLayout
:
class ButtonPanel extends JPanel {
ButtonPanel() {
setLayout(new GridBagLayout());
}
@Override
public Component add(Component button) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridy = nextGridY++;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(3, 3, 3, 3);
super.add(button, gbc);
return button;
}
int nextGridY;
}
Then add this panel to the parent frame or panel (with a BorderLayout
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With