到目前为止,我尽可能避免使用GridBagLayout
(通过手工代码),但这次我无法避免,而我正在阅读SUN的教程GridBagLayout 到目前为止,它并不顺利。我想我是在误解一些事情。
比如我尝试下面的代码(类似于一个在SUN的职位):为什么GridBagLayout将我的组件放在中心而不是放在角落?
public class MainFrame extends JFrame {
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainFrame frame = new MainFrame();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame
*/
public MainFrame() {
super();
setBounds(100, 100, 500, 375);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container mainContainer = getContentPane();
mainContainer.setLayout(new GridBagLayout());
//add label
JLabel someLabel = new JLabel("Label 1:");
GridBagConstraints constraints = new GridBagConstraints();
constraints.gridx = 0;
constraints.gridy = 0;
//constraints.anchor = GridBagConstraints.FIRST_LINE_START;
//constraints.weightx = 0.5;
mainContainer.add(someLabel, constraints);
JTextField someText = new JTextField(30);
constraints = new GridBagConstraints();
constraints.gridx = 1;
constraints.gridy = 0;
constraints.weightx = 0.5;
mainContainer.add(someText, constraints);
//
}
}
我得到的标签,并在框架的中心旁边的其他文本字段之一。
但我期待他们会出现在左上角,因为gridx和gridy对于标签是0。
即使我设置constraints.anchor = GridBagConstraints.FIRST_LINE_START;
仍然是相同的结果。
我错了吗?
来自SUN的文章:
指定组件左上角的行和列。 最左边一列的地址为gridx = 0,最上一行的地址为 gridy = 0。
链接断开。 – mre
@mre:固定链接 – Cratylus
http://madbean.com/anim/totallygridbag/ – keuleJ