gpt4 book ai didi

java - SpringLayout 中的组件大小

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:28:31 25 4
gpt4 key购买 nike

我在表单上使用了 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的宽度很大,我的按钮大小不一样) enter image description here

最佳答案

如果您不关心布局管理器,而只关心布局,那么您应该使用 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 复杂性可能是值得的。

关于java - SpringLayout 中的组件大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18037955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com