将组件设置在页面的中心
如何在面板中央设置组件(比如按钮)?
我使用Flowlayout
将布局约束作为中心,但我在面板的顶部中心位置获得了按钮。
这可以使用AVD 1或BoxLayout
提到的 GridBagLayout
来实现。 有关示例代码,请参阅此答案 。
就个人而言,我会使用GBL,因为需要更少的代码行才能在屏幕上显示组件(在父容器中居中)。
- 我不明白为什么这个答案没有得到更多的投票,但除此之外..
使用GridBagLayout
而不是FlowLayout。
JPanel panel=new JPanel(); panel.setLayout(new GridBagLayout()); panel.add(new JButton("Sample")); // will use default value of GridBagConstraints
使用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); }
如果您开始获得许多按钮或复杂的布局,请考虑使用MigLayout 。