If I add components like JButtons on the east or west side, how do I prevent it from hugging the side of the screen? I want some space between the JButtons and the edge of the screen.
views:
187answers:
3call 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
.)
BorderLayout goes as the name says to the border. You can however nest things inside, so you could insert a JPanel with a border and then put your button in that.
You may also want to experiment with the GUI designer in Netbeans. It is really quite nice, and give a lot of help to things you usually want to do (like have a margin to the border, etc).