简体   繁体   English

将组件设置在页面中心

[英]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 提到的 GridBagLayoutBoxLayout 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,因为只需较少的代码行即可将组件布置在屏幕上(在父容器中居中)。

  1. I do not understand why that answer is not getting more up-votes, but that aside.. 我不明白为什么这个答案没有得到更多的赞成票,而是把它放在一边。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM