我有一些代码可以产生这个:
我希望3,4和5个JTextField位于旁边 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);
}
}
答案 0 :(得分:3)
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
您在几个add(...)
方法调用中没有使用GridBagConstraints。如果您没有告诉它如何放置组件,并且解决方案正如您所期望的那样,GridBagLayout将无法使用,在将组件添加到使用GBL的容器时使用约束对象。