我有一些产生这个的代码:
我希望 3、4 和 5 JTextFields 位于 JLabels 旁边,如 1 和 2 所示。我的代码试图这样做,但上图是结果。
谁能指出我的代码中的问题?
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);
}
}