我有一些生成此代码:
我希望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);
}
}
最佳答案
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的容器中时使用约束对象.