这是我的JPanel类。我有BoxLayout,只添加了一个JLabel。我的JLabel位于屏幕的左侧。有没有办法将BoxLayout中的所有组件与中心对齐。我试过这个:setAlignmentX(CENTER_ALIGNMENT);但它不起作用
public class MainPanel extends JPanel
{
// This layout we will use as our base layout.
private BoxLayout mainLayout = new BoxLayout(this, BoxLayout.Y_AXIS);
// This we will use to control padding in our main panel
EmptyBorder mainBorder = new EmptyBorder(10, 10, 10, 10);
private JLabel title = new JLabel("Podesavanja");
public MainPanel()
{
setLayout(mainLayout);
setBackground(Color.GRAY);
setAlignmentY(CENTER_ALIGNMENT);
// Setting padding
setBorder(mainBorder);
add(title);
}
// Dodajemo sve Ostale panele u ovu main panelu
public static void addPanel(JPanel panel)
{
addPanel(panel);
}
}
答案 0 :(得分:2)
首先,您拨打facebook.userOperations().getUserProfile()
而不是setAlignmentY()
。其次,您在面板上调用它而不是在JLabel上调用它。
修复这两个错误,标签将居中。
答案 1 :(得分:2)
有没有办法为布局内的所有元素做到这一点?
不是head->ptr
。 BoxLayout
使用各个组件的对齐方式。
您可以使用不同的布局管理器:
BoxLayout
允许您使用GridBagLayout
设置对齐方式。您将对齐设置一次,它将被所有组件使用。当然,您需要设置每个组件的gridY。那么这与BoxLayout的x对齐设置有什么不同吗?
您可以像Relative Layout一样使用第三方布局管理器。
它类似于GridBagConstraint
,因为您可以水平或垂直布局组件。但是BoxLayout
还允许您为整个面板指定对齐方式:
RelativeLayout