Reputation: 260
I am writing a program that is meant to use a BorderLayout with two button on the West and East side of the window. Somehow, there is a large gap in the center. Is there any way that I can eliminate this gap and have the two buttons be tangent with each other? Below I have attached my code. Any help is appreciated :).
import java.applet.*;
import java.awt.*;
public class HON extends Applet {
Button p1;
Button p2;
BorderLayout layout;
public void init() {
layout = new BorderLayout();
setLayout(layout);
p1 = new Button("text");
p2 = new Button("text");
add(p1, BorderLayout.WEST);
add(p2, BorderLayout.EAST);
}
public void stop() {
}}
Upvotes: 1
Views: 981
Reputation: 1519
BorderLayout
is doing exactly what the name implies - putting stuff on the border. This is the reason for the gap in the center. If you want to have something that has 2 buttons side by side, I would recommend the GridLayout
for its simplicity. Code would go something like this:
GridLayout layout = new GridLayout(1,2); // Or (2,1), depending on how you want orientation
JPanel pane = new JPanel();
pane.setLayout(layout);
pane.add(leftButton); // Where leftButton is the JButton (or other swing component) on the left
pane.add(rightButton); // Same goes for the right JButton
// Then add your JPanel to the Frame and all that jazz below.
This should do what you want if I understand your question correctly. Notice also that I am using Swing components because they are still maintained by Java. Leave a comment/question if you need any other help with this.
EDIT: Notice in the comments that MadProgrammer suggested using the GridBagLayout
. This is more powerful/versatile than plain vanilla GridLayout
, but also is a bit harder to learn, so you can sort of take your pick as to which you want to do.
Upvotes: 3