![](/img/trans.png)
[英]How do you return the JPanel in the center of a JFrame using a BorderLayout?
[英]How do I center a Component in a JPanel without using BorderLayout? - Java
我认为,您可以使用BorderLayout
将Component
(例如JButton
)放在JPanel
居中:
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易于管理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.