I am trying to implement this layout using GRIDBAG layout in java
public static void addComponentsToPane(Container pane) {
if (RIGHT_TO_LEFT) {
pane.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
}
JLabel label1,label2,label3,result,title;
JButton calculate_btn;
JTextField side1,side2,side3;
pane.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
if (shouldFill) {
//natural height, maximum width
c.fill = GridBagConstraints.HORIZONTAL;
}
title = new JLabel("Area of Triangle");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 2;
c.gridy = -1;
pane.add(title, c);
label1 = new JLabel("Side 1: ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 1;
c.gridy = 1;
pane.add(label1, c);
label2 = new JLabel("Side 2: ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 1;
c.gridy = 2;
pane.add(label2, c);
label3 = new JLabel("Side 3: ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 1;
c.gridy = 3;
pane.add(label3, c);
side1 = new JTextField(" ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 2;
c.gridy = 1;
pane.add(side1, c);
side2 = new JTextField("Side 3: ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 2;
c.gridy = 2;
pane.add(side2, c);
side3 = new JTextField("Side 3: ");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 2;
c.gridy = 3;
pane.add(side3, c);
calculate_btn = new JButton("Calculate");
//c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 30; //make this component tall
c.weightx = 0.5;
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 5;
pane.add(calculate_btn, c);
result = new JLabel("Result displayed here");
if (shouldWeightX) {
c.weightx = 0.5;
}
c.fill = GridBagConstraints.HORIZONTAL;
c.ipady = 20;
c.gridx = 2;
c.gridy = 7;
pane.add(result, c);
}
So the code above is basically just the components that will be added to a GUI, but I am not quite getting what I want, this is what I am trying to achieve
But this is what I am getting with the above code
So when I compile the above is what I endup with, also if possible I dont want the user to resize the window, I am guessing some boolean with one of the window properties..
The problem is that your are setting ipady
which "stretches" your component vertically. You are probably looking for the insets
property: http://docs.oracle.com/javase/7/docs/api/java/awt/GridBagConstraints.html#insets
Try using this:
c.insets = new Insets(10, 0, 10, 0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With