我正在使用GridBagLayout作为面板,我有一个标签调用show_date_info,我想将它放在第3行的中间(gridy = 2),但它出现在最左边。或者我必须通过设置标签的gridx来实现这一点。感谢。
setLayout(new GridBagLayout());
c.anchor = GridBagConstraints.NORTHEAST;
c.weighty = 0;
c.weightx = 1;
c.insets = new Insets(10,0,0,0);
c.gridx = 5;
c.gridy = 0;
c.gridwidth = 1;
add(Logoutbtn, c);
c = new GridBagConstraints();
c.weighty = 1;
c.weightx = 0.1;
c.insets = new Insets(80,180,0,0);
c.gridx = 1;
c.gridy = 1;
c.gridwidth = 1;
add(startdatelabel, c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 1;
c.weightx = 1;
c.insets = new Insets(80,0,0,80);
c.gridx = 2;
c.gridy = 1;
c.gridwidth = 1;
add(picker1, c);
c = new GridBagConstraints();
c.weighty = 1;
c.weightx = 0.1;
c.insets = new Insets(80,80,0,0);
c.gridx = 4;
c.gridy = 1;
c.gridwidth = 1;
add(enddatelabel, c);
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 1;
c.weightx = 1;
c.insets = new Insets(80,0,0,180);
c.gridx = 5;
c.gridy = 1;
c.gridwidth = 1;
add(picker2, c);
c = new GridBagConstraints();
c.anchor = GridBagConstraints.CENTER;
c.fill = GridBagConstraints.REMAINDER;
c.insets = new Insets(-80,0,0,0);
c.gridy = 2;
//c.gridwidth = 1;
add(show_date_info, c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weighty = 1;
c.weightx = 1;
c.insets = new Insets(0,20,0,20);
c.gridx = 0;
c.gridy = 3;
c.gridwidth = 7;
add(sp,c);
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(-100,10,0,10);
c.gridx = 5;
c.gridy = 4;
c.gridwidth = 1;
add(confirmbtn,c);
答案 0 :(得分:1)
无需创建GridBagConstraints
的不同对象。只需创建单个对象并使用它。
确保
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1; // 100%
c.gridy = 2 // 3rd row
c.gridwidth = max_number_of_columns;
使用JLabel(text,horizontalAlignement)
例如
new JLabel("In center",SwingConstants.CENTER) // to keep label in center