我正在搞亂GridBagLayout。我已經有所瞭解,因此能夠做出這種佈局。但我的原來是不符合我的應該。這裏是屏幕。無法準確理解什麼以及如何使用GridBagConstraints。 As-Is vs. Should-Be
AS-是:(
應該是:■
我明白,我必須調整它一下,讓大小設置(setSize()
)但真正棘手。其中一個是讓「添加聯繫人」JLabel
位於最上方的中心位置
正在等待您的回覆。
package SimpleCRUD;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
@SuppressWarnings("serial")
public class ContactListFrame extends JFrame{
JButton Button1, Button2;
JTextField textField1, textField2, textField3;
JLabel label1, label2, label3 , label4;
GridBagLayout layout = new GridBagLayout();
GridBagConstraints Constraint = new GridBagConstraints();
public ContactListFrame() {
super("All Contacts");
Button1 = new JButton("Add");
Button2 = new JButton("Cancel");
textField1 = new JTextField(15);
textField2 = new JTextField(15);
textField3 = new JTextField(15);
label4 = new JLabel("Add Contact");
label4.setFont (new Font("fallan", 1, 25));
label1 = new JLabel("First Name:");
label2 = new JLabel("Last Name:");
label3 = new JLabel("Phone Number:");
setLayout(layout);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setSize(400, 200);
setResizable(false);
Constraint.fill = GridBagConstraints.NONE;
Constraint.anchor = GridBagConstraints.NORTH;
addComponent(label4, 0, 1, 1, 1);
addComponent(textField1, 1, 1, 1, 1);
addComponent(textField2, 2, 1, 1, 1);
addComponent(textField3, 3, 1, 1, 1);
addComponent(label1, 1, 0, 1, 1);
addComponent(label2, 2, 0, 1, 1);
addComponent(label3, 3, 0, 1, 1);
addComponent(Button1, 4, 0, 2, 1);
addComponent(Button2, 4, 1, 2, 1);
}
public void addComponent (Component comp, int row, int col, int width, int height){
Constraint.gridx = col;
Constraint.gridy = row;
Constraint.gridwidth = width;
Constraint.gridheight = height;
layout.setConstraints(comp, Constraint);
add(comp);
}
}
我們可以看到,正在生成佈局的代碼? – 2011-05-03 15:25:36
您是否使用SwingConstants.CENTER構建了「添加聯繫人」JLabel作爲第二個參數?你玩過gridwidth嗎? – Doug 2011-05-03 15:28:38
您可能還想看看Java 6引入的GroupLayout - 它可以完成GrindBagLayout所做的大部分工作,而且IMO更易於使用。 – 2011-05-03 15:30:05