[英]Set component at center of the page
How can I set a component (say button) at center of the panel? 如何在面板中央设置组件(例如按钮)?
I used Flowlayout
with layout constraint as center, but I am getting button at top-center position of the panel. 我使用以布局约束为中心的Flowlayout
,但在面板的顶部中心位置获得了按钮。
This can be achieved using either GridBagLayout
as mentioned by AVD 1 or BoxLayout
. 可以使用AVD 1 提到的 GridBagLayout
或BoxLayout
。 See this answer for sample code. 请参阅此答案以获取示例代码。
Personally I'd use GBL for this because fewer lines of code are required to get the component laid out & on-screen (centered in the parent container). 就我个人而言,我将使用GBL,因为只需较少的代码行即可将组件布置在屏幕上(在父容器中居中)。
Use GridBagLayout
instead of FlowLayout. 使用GridBagLayout
代替FlowLayout。
JPanel panel=new JPanel();
panel.setLayout(new GridBagLayout());
panel.add(new JButton("Sample")); // will use default value of GridBagConstraints
Use a null
layout and set the button's bounds, like this: 使用null
布局并设置按钮的边界,如下所示:
// assuming you're extending JPanel
private JButton button; // data field
...
this.setLayout(null);
this.addComponentListener(new ComponentAdapter(){
public void componentResized(ComponentEvent e){
setButtonBounds();
}
});
private void setButtonBounds(){
int bw = 90; // button width
int bh = 30; // button height
int w = getWidth();
int h = getHeight();
button.setBounds((w - bw) / 2, (h - bh) / 2, bw, bh);
}
If you start getting many buttons or a complex layout, consider using MigLayout . 如果您开始获得许多按钮或复杂的布局,请考虑使用MigLayout 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.