【发布时间】:2014-05-06 00:50:53
【问题描述】:
1.关于 GridBagLayout 的问题:- 尽管为所有组件设置了 gridx=0;,但它们都在父组件的中心对齐。 请告诉我如何解决它,并请告诉我为什么会发生这种意外行为。
2。关于 FlowLayout 的问题:-
在示例的开头,一个面板(添加到父级的顶部 带有 GridBagLayout 的面板)正在使用
FlowLayout。根据 文档中,构造函数FlowLayout(FlowLayout.LEFT, 5, 5)、FlowLayout.LEFT用于对齐,接下来的两个int是 对于hgap和vgap。 我正在使用左对齐,但仍然两者都使用 按钮出现在中间。请告诉我为什么?所有组件的垂直插入比预期的要多得多。 为什么会这样?相同的 5 值不会导致侧面有太多的插入:s
示例代码:-
Card(){
setLayout(new GridBagLayout());
JPanel panelBtns= new JPanel();
panelBtns.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));
JButton emailBtn= new JButton("a");
JButton saveBtn= new JButton("b");
panelBtns.add(emailBtn);
panelBtns.add(saveBtn);
GridBagConstraints c= new GridBagConstraints();
c.gridx=0;
c.gridy=0;
c.insets= new Insets(5,5,5,5);
c.weightx=1;
c.weighty=1;
add(panelBtns, c);
JLabel labelTitle= new JLabel("Title");
labelTitle.setFont(new Font("calibri", Font.PLAIN, 12));
c= new GridBagConstraints();
c.gridx=0;
c.gridy=1;
c.insets=new Insets(5,5,5,5);
c.weightx=0.35;
c.weighty=1;
add(labelTitle, c);
JTextField textField= new JTextField();
Border border = BorderFactory.createLineBorder(Color.GRAY);
textField.setBorder(BorderFactory.createCompoundBorder(border,
BorderFactory.createEmptyBorder(2,2,2,2)));
c= new GridBagConstraints();
c.gridx=0;
c.gridy=2;
c.insets= new Insets(5,5,5,5);
c.fill=c.HORIZONTAL;
c.weightx= 1;
c.weighty=1;
add(textField,c);
JLabel bodyLabel= new JLabel("Detail");
bodyLabel.setFont(new Font("calibri", Font.PLAIN, 12));
c= new GridBagConstraints();
c.gridx=0;
c.gridy=3;
c.insets=new Insets(5,5,5,5);
c.weightx=1;
c.weighty=1;
add(bodyLabel, c);
JTextArea textArea= new JTextArea();
Border border1 = BorderFactory.createLineBorder(Color.GRAY);
textArea.setBorder(BorderFactory.createCompoundBorder(border1,
BorderFactory.createEmptyBorder(2,2,2,2)));
c= new GridBagConstraints();
c.gridx=0;
c.gridy=4;
c.insets= new Insets(5, 5, 5,5);
c.fill=c.BOTH;
c.weightx=1;
c.weighty=10;
add(textArea,c);
}
编辑:-
我更改了 insets 的值,但 组件上方和下方的不需要的 inset 仍然存在...这里看起来几乎没问题,因为我在此屏幕截图中使用了较小的帧大小,但是当框架更大,它看起来很丑而且错位。
我希望panelBtns 和titleLabel 之间的差距更小,而textFielf 和titleLabel 之间的差距更小……bodyLabel 和textArea 也是如此。
c.insets= new Insets(2,2,0,2); // panelBtns
c.insets=new Insets(0,5,0,5); //titleLabel
c.insets= new Insets(0,5,0,5); //textField
c.insets=new Insets(0,5,0,5); //bodyLabel
c.insets= new Insets(0, 5, 5,5); //textArea
【问题讨论】:
标签: java swing user-interface gridbaglayout flowlayout