java jpanel无法生成包含7行和2列的gridlayout
我想问问我的代码是否出了问题。我已经用borderlayout
设置了框架。在中间部分,我想使用gridlayout
,里面有7行和2列
paneltengah= new JPanel();
paneltengah.setLayout(new GridLayout(7,2));
labelname = new JLabel(lbl_name,SwingConstants.LEFT);
labelusername = new JLabel(lbl_username,SwingConstants.LEFT);
labelpassword = new JLabel(lbl_password,SwingConstants.LEFT);
labelgender = new JLabel(lbl_gender,SwingConstants.LEFT);
labelemail = new JLabel(lbl_email,SwingConstants.LEFT);
labelhobby = new JLabel(lbl_hobby,SwingConstants.LEFT);
labelrole = new JLabel(lbl_role,SwingConstants.LEFT);
textname = new JTextField(20);
textusername = new JTextField(20);
textpassword = new JPasswordField(20);
textemail = new JTextField(20);
comboboxhobby = new JComboBox();
comboboxrole = new JComboBox();
radiobuttonmale = new JRadioButton("Male");
radiobuttonfemale = new JRadioButton("Female");
ButtonGroup btngroup = new ButtonGroup();
btngroup.add(radiobuttonmale);
btngroup.add(radiobuttonfemale);
paneltengah.add(labelname);
paneltengah.add(labelusername);
paneltengah.add(labelpassword);
paneltengah.add(labelgender);
paneltengah.add(labelemail);
paneltengah.add(labelrole);
paneltengah.add(labelhobby);
//// paneltengah.add(textname); when i open this, the layout become awkward
//// paneltengah.add(textusername);
//// paneltengah.add(textpassword);
//// paneltengah.add(radiobuttonmale);
//// paneltengah.add(radiobuttonfemale);
//// paneltengah.add(comboboxhobby);
//// paneltengah.add(comboboxrole);
pane.add(paneltengah, BorderLayout.CENTER);
下面的图片显示在不打开评论的情况下
下图显示为取消注释
我的代码怎么了
# 1 楼答案
首先,
GridLayout
在其关联的Container
中均匀地调整所有组件的大小,这解释了为什么标签和字段的大小都相同。例如,如果在JPanel
中有JTextArea
200列×20行,那么即使是最小的标签也会占用那么大的空间接下来,根据
GridLayout
Javadoc,当用两个非零参数构造GridLayout
实例时,行数固定,列数根据放入父Container
的组件数进行调整我建议使用
BorderLayout
来设置主表单布局。把你的标题放在NORTH
,并保留标签和字段的CENTER
(你当前的JPanel
)对于标签和字段,最简单的解决方案可能是使用
GridLayout(0, 2)
(固定列数)。但所有组件的大小仍然相同如果您需要更多地控制组件的大小(例如,字段比标签宽),那么我建议使用另一个布局管理器,例如
GridBagLayout
。我知道管理起来更复杂,但使用GridBagLayout
格式预览实用程序应该会有所帮助。这样一个程序可能被命名为GridBagLab
(我知道David Geary的书Graphic Java第2卷——Swing的特色之一在它的配套CD上)在https://www.youtube.com/watch?v=Ts5fsHXIuvI还有一个
GridBagLayout
教程