我想,你可以使用Component
将JButton
(例如JPanel
)放在BorderLayout
中心:
panel.setLayout(new BorderLayout());
panel.add(button, BorderLayout.CENTER);
但是,JButton
占据了JPanel
的所有空间。
例如可以使用另一个LayoutManager
,还是有更简单的方法来使JButton
居中?
我认为,button.setAlignmentX(JButton.CENTER_ALIGNMENT)
不起作用。
我想大多数任务只是个人选择/老板的命令,如果你使用布局管理器而不是其他人。有一些布局管理器可以完成所有要求,例如GridBadLayout,但我个人认为在大多数情况下它们不是最好的选择,因为它们最终可能会使事情过于复杂。对于这个特定的任务,我会选择BoxLayout https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
并将编码类似于:
import java.awt.*;
import javax.swing.*;
public class CenteredButton extends JFrame {
public CenteredButton() {
Container pane = getContentPane();
pane.setLayout(new BoxLayout(pane, BoxLayout.PAGE_AXIS));
JPanel panel = new JPanel();
JButton button = new JButton("Button1");
button.setPreferredSize(new Dimension(100, 50));
panel.add(button);
pane.add(panel);
pack();
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new CenteredButton();
}
}
您可能会注意到,调整按钮尺寸的大小不会改变它粘在框架中间的事实。
PS:开发商的意见主要是热衷于http://www.miglayout.com/和https://tips4java.wordpress.com/2008/11/02/relative-layout/。在我看来,这两者都比GridBagLayout更容易管理