So far I managed to avoid using the GridBagLayout
(by hand code) as much as possible, but I could not avoid it this time and I am reading the SUN's tutorial GridBagLayout
So far it is not going well. I think I am missunderstanding something.
For example I try the following code (similar to the one in SUN's post):
public class MainFrame extends JFrame {
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame
*/
public MainFrame() {
super();
setBounds(100, 100, 500, 375);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container mainContainer = getContentPane();
mainContainer.setLayout(new GridBagLayout());
//add label
JLabel someLabel = new JLabel("Label 1:");
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
//constraints.anchor = GridBagConstraints.FIRST_LINE_START;
//constraints.weightx = 0.5;
mainContainer.add(someLabel, constraints);
JTextField someText = new JTextField(30);
constraints = new GridBagConstraints();
constraints.gridx = 1;
constraints.gridy = 0;
constraints.weightx = 0.5;
mainContainer.add(someText, constraints);
//
}
}
I get the label and the textfield one next to the other in the center of the frame.
But I was expecting that they would show up in the top left corner since the gridx and gridy is 0 for the label.
Even if I set constraints.anchor = GridBagConstraints.FIRST_LINE_START;
still the same result.
Am I wrong here?
From the SUN's post:
Specify the row and column at the upper left of the component. The leftmost column has address gridx=0 and the top row has address gridy=0.
constraints.weighty=1
to the label as well and anchor to the labelFIRST_LINE_START
.But what does the value 1 in weighty actually mean? – Havildar