Set component at center of the page

前端 未结 3 1770
天涯浪人
天涯浪人 2020-12-12 07:01

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

相关标签:
3条回答
  • 2020-12-12 07:49

    Use GridBagLayout instead of FlowLayout.

    JPanel panel=new JPanel();
    panel.setLayout(new GridBagLayout());
    panel.add(new JButton("Sample")); // will use default value of GridBagConstraints
    
    0 讨论(0)
  • 2020-12-12 08:01

    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.

    0 讨论(0)
  • 2020-12-12 08:04

    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..
    0 讨论(0)
提交回复
热议问题