3
votes

I have some code that produces this:

example thing

Where I want the 3, 4, and 5 JTextFields to be beside The JLabels, as in 1 and 2. My Code is an attempt to do so, but the above image is the result.

Can anyone point out the problem in my code?

import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

 public class example{  
       public static void main(String[] args){

        JDialog jd = new JDialog();
    jd.setTitle("Example");
    GridBagLayout gl = new GridBagLayout();
    final JTextField j1 = new JTextField("1");
    final JTextField j2 = new JTextField("2");
    final JTextField j3 = new JTextField("3");
    final JTextField j4 = new JTextField("4");
    final JTextField j5 = new JTextField("5");
    jd.setLayout(gl);
    GridBagConstraints c = new GridBagConstraints();
    c.fill = GridBagConstraints.BOTH;
    c.weightx = 1.0;
    c.weighty = 1.0;
    c.gridx = 0;
    c.gridy = 0;
    jd.add(new JLabel("TextField 1: "), c);
    c.gridx = 1;
    jd.add(j1,c);
    c.gridx = 0;
    c.gridy++;
    jd.add(new JLabel("TextField 2: "), c);
    c.gridx = 1;
    c.gridy=1;
    jd.add(j2,c);
    c.gridx = 0;
    c.gridy++;
    jd.add(new JLabel("TextField 3: "), c);
    c.gridx = 1;
    jd.add(j3);
    c.gridx = 0;
    c.gridy++;
    jd.add(new JLabel("TextField 4: "), c);
    c.gridx = 1;
    jd.add(j4);
    c.gridx = 0;
    c.gridy++;
    jd.add(new JLabel("TextField 5: "), c);
    c.gridx = 1;
    jd.add(j5);


    jd.pack();
    jd.setVisible(true);
       }
 } 
1

1 Answers

3
votes
jd.add(j3);    // **** here
c.gridx = 0;
c.gridy++;
jd.add(new JLabel("TextField 4: "), c);
c.gridx = 1;
jd.add(j4);    // **** here
c.gridx = 0;
c.gridy++;
jd.add(new JLabel("TextField 5: "), c);
c.gridx = 1;
jd.add(j5);    // **** here

You're not using the GridBagConstraints in several of your add(...) method calls. The GridBagLayout won't work if you don't tell it how to place the components, and the solution is as you'd expect, to use the constraints object when adding a component to a GBL-using container.