问题
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).
- 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