更新时间:2023-12-05 23:02:52
您的问题是关于GridLayout
的,但是您使用BorderLayout
显示代码:
Your question is about GridLayout
but you show code using BorderLayout
:
buttonPanel = new JPanel(new BorderLayout());
button = new JButton("Display Color");
button.addActionListener(new ButtonListener ()); // Add event handler
button.setFont(font);
button.setPreferredSize(new Dimension(100, 100));
?
该按钮始终会填满整个面板,而如果我删除 gridlayout,该按钮将不会具有相同的行为.
The button always fills up the whole panel, whereas if I remove the gridlayout, the button won't have the same behavior.
这是GridLayout
的默认行为,它的空间被平均分配,并且每个组件都占满了整个空间(BorderLayout
会使用相同的空间).
This is GridLayout
default behavior, it space is divided equally and each component takes up the full space (same would apply for BorderLayout
).
还有许多其他LayoutManager
可以满足您的需求:
There are many other LayoutManager
s which will will meet your needs:
您可能希望查看 GridBagLayout
更灵活:
You may want to look at GridBagLayout
which is more flexible:
buttonPanel = new JPanel(new GridBagLayout());
button = new JButton("Display Color");
button.addActionListener(new ButtonListener()); // Add event handler
button.setFont(font);
GridBagConstraints gc=new GridBagConstraints();
gc.fill=GridBagConstraints.HORIZONTAL;
gc.gridx=0;
gc.gridy=0;
buttonPanel.add(button,gc);
,甚至是默认的JPanel
FlowLayout
:
buttonPanel = new JPanel();
button = new JButton("Display Color");
button.addActionListener(new ButtonListener()); // Add event handler
button.setFont(font);
buttonPanel.add(button);
或第三方LayoutManger
,例如 MigLayout
.
Or a 3rd party LayoutManger
like MigLayout
.
其他建议
不要调用setPreferredSize(..)
而不是覆盖getPreferredSize()
,甚至不仅仅在绘制到Graphic
s对象或想要使组件更大/更小时才这样做,不要出于布局目的而这么做,那就是
Dont call setPreferredSize(..)
rather override getPreferredSize()
and even than only do this when painting to the Graphic
s object or wanting to make a component bigger/smaller dont do this for Layout purposes thats a LayoutManager
s job.