[英]How do I center a Component in a JPanel without using BorderLayout? - Java
I think, that you can center a Component
(for Example a JButton
) in a JPanel
, using the BorderLayout
: 我认为,您可以使用
BorderLayout
将Component
(例如JButton
)放在JPanel
居中:
panel.setLayout(new BorderLayout());
panel.add(button, BorderLayout.CENTER);
But than the JButton
takes up all the space in the JPanel
. 但是,比
JButton
占用了JPanel
中的所有空间。
Is it for example possible to use another LayoutManager
, or is there an even easyer way to do center the JButton
? 例如,是否可以使用另一个
LayoutManager
,或者是否有更简单的方法来居中JButton
?
I think, button.setAlignmentX(JButton.CENTER_ALIGNMENT)
doesn't work. 我认为
button.setAlignmentX(JButton.CENTER_ALIGNMENT)
不起作用。
I guess with most tasks it's just a matter of personal choice/your boss's order if you're using a Layout manager rather than the others. 我猜对于大多数任务来说,如果您使用的是布局管理器而不是其他人,则只是个人选择/老板的命令。 There are some Layout managers that can accomplish quite every requirement, such as GridBadLayout, but i personally think that in most situation they're not the best choice since they might end up overcomplicating things.
有一些布局管理器可以满足几乎所有要求,例如GridBadLayout,但我个人认为,在大多数情况下,它们并不是最佳选择,因为它们最终可能会使事情变得过于复杂。 For this specific task i would go with a BoxLayout https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
对于此特定任务,我将使用BoxLayout https://docs.oracle.com/javase/tutorial/uiswing/layout/box.html
And would code something like: 并会编写如下代码:
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();
}
}
As you may notice, resizing the button's dimension will not change the fact that it sticks in the middle of the frame. 您可能会注意到,调整按钮尺寸的大小不会改变它停留在框架中间的事实。
PS: developers opinions are mostly enthusiastic about http://www.miglayout.com/ and https://tips4java.wordpress.com/2008/11/02/relative-layout/ . PS:开发人员的意见主要是http://www.miglayout.com/和https://tips4java.wordpress.com/2008/11/02/relative-layout/ 。 Both of these, in my opinion, are easier to manage than GridBagLayout
我认为,这两种方法都比GridBagLayout易于管理
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.