如何在JPanel

时间:2016-10-31 23:01:25

标签: java swing jpanel padding

这是我的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);
}
}

2 个答案:

答案 0 :(得分:2)

首先,您拨打facebook.userOperations().getUserProfile()而不是setAlignmentY()。其次,您在面板上调用它而不是在JLabel上调用它。

修复这两个错误,标签将居中。

答案 1 :(得分:2)

  

有没有办法为布局内的所有元素做到这一点?

不是head->ptrBoxLayout使用各个组件的对齐方式。

您可以使用不同的布局管理器:

  1. BoxLayout允许您使用GridBagLayout设置对齐方式。您将对齐设置一次,它将被所有组件使用。当然,您需要设置每个组件的gridY。那么这与BoxLayout的x对齐设置有什么不同吗?

  2. 您可以像Relative Layout一样使用第三方布局管理器。

  3. 它类似于GridBagConstraint,因为您可以水平或垂直布局组件。但是BoxLayout还允许您为整个面板指定对齐方式:

    RelativeLayout