Set component at center of the page

我只是一个虾纸丫 提交于 2019-11-28 14:43:44
Andrew Thompson

This can be achieved using either GridBagLayout as mentioned by AVD1 or 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).

  1. I do not understand why that answer is not getting more up-votes, but that aside..

Use GridBagLayout instead of 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:

// 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!