我想手动创建一个JFrame并使用spring布局来执行此操作。但是,我的最终输出并不好。我的行之间的空间太大了,我的单选按钮之间也是如此:
我的代码:
public final class NewUserFrame1 extends JFrame {
public NewUserFrame1() {
add(rowComponent(), BorderLayout.CENTER);
setLocation(200, 40);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
pack();
}
public JPanel rowComponent() {
JPanel panel = new JPanel();
JLabel fnamelbl = new JLabel("First name");
JLabel lnamelbl = new JLabel("Last Name");
JLabel fntemp = new JLabel();
JLabel lntemp = new JLabel();
JTextField fntf = new JTextField(10);
JTextField lntf = new JTextField(10);
JLabel gndlnl = new JLabel("Gender");
JRadioButton malerb = new JRadioButton("Male");
JRadioButton femalerb = new JRadioButton("Female");
ButtonGroup bgroup = new ButtonGroup();
bgroup.add(malerb);
bgroup.add(femalerb);
JLabel registnm = new JLabel("Registration ID is:");
JLabel showreglbl = new JLabel();
JLabel regtemp = new JLabel();
panel.add(fnamelbl);
panel.add(fntf);
panel.add(fntemp);
panel.add(lnamelbl);
panel.add(lntf);
panel.add(lntemp);
panel.add(gndlnl);
panel.add(malerb);
panel.add(femalerb);
panel.add(registnm);
panel.add(showreglbl);
panel.add(regtemp);
panel.setLayout(new SpringLayout());
SpringUtilities.makeCompactGrid(panel, 4, 3, 50, 15, 3, 4);
return panel;
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
NewUserFrame1 newUserFrame1 = new NewUserFrame1();
}
});
}
}
现在:
答案 0 :(得分:1)
您写道:
SpringUtilities.makeCompactGrid(面板,4,3,50,15,3,100);
最后一个参数是yPad。将其更改为10(或更低值,如果需要),例如:
SpringUtilities.makeCompactGrid(panel, 4, 3, 50, 15, 3, 10);
但仍然 - 标签将是高等等,但这是一个不同的问题。继续玩面板的大小和组件的大小。
如果是单选按钮 - 更改
panel.add(malerb);
panel.add(femalerb);
类似于:
JPanel radioPanel = new JPanel();
radioPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
radioPanel.add(malerb);
radioPanel.add(femalerb);
panel.add(radioPanel);
panel.add(new JLabel());
需要最后一行,因为您声明布局有3列。
答案 1 :(得分:1)
而不是在setSize
构造函数中的pack
上调用JFrame
来电NewUserFrame1
。
public NewUserFrame1() {
add(rowComponent(), BorderLayout.CENTER);
setLocation(200, 40);
//setSize(800, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
pack();
}
还可以通过以下方式更改SpringUtilities.makeCompactGrid
方法的参数:
SpringUtilities.makeCompactGrid(panel, 4, 3, 50, 15, 3, 4);//change yPad to 4 instead of 100. It sets the vertical height between two rows