Hi i am beginner to java and doing small GUI using GridBagLayout. See the attached code and also the output . what i want is to place the JButtons on top left corner as per the position assigned in gridx and gridy . But it placing components in center instead of top left as expected , if i use Insets , gridx /gridy all that is working but not from proper coordinates so please see attached code and image and guide me about it
public rect()
{
JPanel panel = new JPanel( new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
JButton nb1= new JButton("Button1 ");
JButton nb2= new JButton("Button2 ");
gbc.gridx=0;
gbc.gridy=0 ;
panel.add(nb1, gbc);
gbc.gridx=1;
gbc.gridy=1;
panel.add(nb2, gbc);
panel.setVisible(true);
JFrame frame = new JFrame("Address Book ");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300 );
frame.add(panel);
frame.setVisible(true);
}
OUTPUT : want these buttons on top left please guide me
I think the problem is more the use of setSize(..)
, you should rather use appropriate LayoutManager
and call pack()
on JFrame
instance after adding all components to JFrame
and before setting JFrame
visible, also no need for panel.setVisible(..)
:
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JPanel panel = new JPanel(new GridBagLayout());
JButton nb1 = new JButton("Button1 ");
JButton nb2 = new JButton("Button2 ");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(nb1, gbc);
gbc.gridx = 1;
gbc.gridy = 1;
panel.add(nb2, gbc);
JFrame frame = new JFrame("Address Book ");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
});
}