[英]Component size in SpringLayout
我在我的表單上使用SpringLayout,但正如你所看到的,它的外觀不好(大而大)!
public class t8 extends JFrame {
JButton okButton, cancellButton;
JTextField idTF, nameTf;
JLabel idlbl, namelbl;
public t8() {
add(createPanel(), BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 500);
setLocation(400, 100);
setVisible(true);
}
public static void main(String[] args) {
new t8();
}
public JPanel createPanel() {
JPanel panel = new JPanel();
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
panel.add(idlbl);
panel.add(idTF);
panel.add(namelbl);
panel.add(nameTf);
panel.add(okButton);
panel.add(cancellButton);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 3, 2, 20, 50, 50, 100);
return panel;
}
}
我更改了makeCompactGrid
數字,但沒有成功!
( JTextFields
的寬度很大,我的按鈕的大小也不同)
我建議你使用Netbeans拖放工具,它允許你在物理上設置組件,也會給你預覽。 如果你想用代碼做,只需使用自由布局並手動設置每個組件的位置和大小通過setSize()和setLocation()方法,雖然這將需要更多行代碼,但將確保所有組件都是在他們正確的位置。
如果您不關心布局管理器,但只關心布局,那么您應該使用GridLayout
,或者如果您不希望所有組件都具有相同的大小,那么GridBagLayout
。 以下是網格布局的方法(僅顯示修改后的方法):
public JPanel createPanel() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
panel.add(idlbl);
panel.add(idTF);
panel.add(namelbl);
panel.add(nameTf);
panel.add(okButton);
panel.add(cancellButton);
return panel;
}
並使用GridBagLayout
:
public JPanel createPanel() {
JPanel panel = new JPanel();
GridBagLayout gb = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
panel.setLayout(gb);
okButton = new JButton("Ok");
cancellButton = new JButton("Cancel");
idTF = new JTextField(10);
nameTf = new JTextField(10);
idlbl = new JLabel("ID");
namelbl = new JLabel("Name");
add(panel, idlbl, 0, 0, 1, 1, gb, gbc, false);
add(panel, idTF, 0, 1, 1, 1, gb, gbc, true);
add(panel, namelbl, 1, 0, 1, 1, gb, gbc, false);
add(panel, nameTf, 1, 1, 1, 1, gb, gbc, true);
add(panel, okButton, 2, 0, 1, 1, gb, gbc, false);
add(panel, cancellButton, 2, 1, 1, 1, gb, gbc, true);
return panel;
}
private void add(Container outer, Component c, int x, int y, int w, int h, GridBagLayout gb, GridBagConstraints gbc, boolean wide) {
gbc.gridx = x;
gbc.gridy = y;
gbc.gridwidth = w;
gbc.gridheight = h;
if (wide) {
gbc.weightx = 100;
} else {
gbc.weightx = 0;
}
gb.setConstraints(c, gbc);
outer.add(c);
}
我相信額外的GridBagLayout
復雜性可能是值得的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.