Set component at center of the page

老子叫甜甜 提交于 2019-11-27 08:48:50

问题


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.


回答1:


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



回答2:


Use GridBagLayout instead of FlowLayout.

JPanel panel=new JPanel();
panel.setLayout(new GridBagLayout());
panel.add(new JButton("Sample")); // will use default value of GridBagConstraints



回答3:


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.



来源:https://stackoverflow.com/questions/9090609/set-component-at-center-of-the-page

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