I am trying to place two JButtons next to each other in the center of a JFrame, that won’t re-size the buttons when the JFrame is re-sized.
To do this I placed the two buttons in a panel with a FlowLayout, that is then placed in a panel with a center BorderLayout.
However the following code won’t display the chosen panel in the center of the BorderLayout.
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class test extends JFrame {
private JPanel panel1 = new JPanel();
private JPanel panel2 = new JPanel();
private JButton button1 = new JButton("one");
private JButton button2 = new JButton("two");
public test() {
panel1.setLayout(new FlowLayout());
panel1.add(button1);
panel1.add(button2);
panel2.setLayout(new BorderLayout());
panel2.add(panel1, BorderLayout.CENTER);
this.add(panel2);
}
public static void main(String[] args) {
test frame = new test();
frame.setVisible(true);
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Set
GridBagLayouttopanel1.EDIT:
@trashgod : I have to figure out how the default constraints do it.
Because of the field GridBagLayout.defaultConstraints :
In normal practice, one must have to create
GridBagConstraintsobject and set fields to specify the constraints on each object.To quote the tutorial: