简体   繁体   English

布局内的布局

[英]Layout inside Layout

I have a JPanel with a vertical BoxLayout, for one element i want to be able to use another BoxLayout which places elements horisontally. 我有一个带有垂直BoxLayout的JPanel,对于一个元素,我希望能够使用另一个可以放置元素的BoxLayout。 The code will explain what i'm trying to do: 代码将解释我正在尝试做什么:

private void prepareGUI() {
    setBorder(new EmptyBorder(20, 0, 20, 0));
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    JLabel lblTitle = new JLabel("Downloading");
    lblTitle.setFont(new Font("Arial", Font.PLAIN, 20));
    lblTitle.setAlignmentX(Component.CENTER_ALIGNMENT);

    add(lblTitle);

    Component verticalStrut = Box.createVerticalStrut(20);
    add(verticalStrut);

    JProgressBar progressBar = new JProgressBar();
    progressBar.setStringPainted(true);
    progressBar.setBorder(null);
    progressBar.setValue(50);

    Dimension size = new Dimension(300, 25);
    progressBar.setMinimumSize(size);
    progressBar.setMaximumSize(size);
    progressBar.setPreferredSize(size);
    add(progressBar);

    BoxLayout textLayout = new BoxLayout(this, BoxLayout.Y_AXIS);

    JLabel lblTest_1 = new JLabel("Test 1!");
    textLayout.add(lblTest_1);

    JLabel lblTest_2 = new JLabel("Test 2!");
    textLayout.add(lblTest_2);

    add(textLayout);
}

Now obviously this isn't possible as BoxLayout isn't a Container (It even asks for the container to be linked to on construction. My question is what is the best way to achieve what i want? Should i create another JPanel and put that inside the first JPanel? I was thinking that but it seems a little too complicated, there must be a simpler way? 现在显然这是不可能的,因为BoxLayout不是一个容器(它甚至要求容器链接到构造。我的问题是什么是实现我想要的最好的方法?我应该创建另一个JPanel并把它放第一个JPanel里面?我在想,但似乎有点过于复杂,必须有一个更简单的方法吗?

BoxLayout is not a container, it's a LayoutManager, so, components can't be added to BoxLayout since box layout is not inheriting anything from abstract class Component , it's will add to some container like JPanel or frame's container.... BoxLayout不是一个容器,它是一个LayoutManager,因此,组件无法添加到BoxLayout因为框布局不是从抽象类Component继承任何东西,它会添加到某些容器,如JPanel或框架的容器....

So, it's wrong to say: 所以说:这是错的:

 textLayout.add(lblTest_1);

Or even 甚至

add(textLayout);

Because this method addes a component to the frame's container, and BoxLayout is not a component. 因为此方法将组件添加到框架的容器中,而BoxLayout不是组件。


Should i create another JPanel and put that inside the first JPanel? 我应该创建另一个JPanel并将其放在第一个JPanel中吗?

Except what you did and avoiding null layout, you're free to do anything, as, design is upon to you, as far as I am preferring multiple panels if wanted. 除了你做了什么并避免null布局,你可以自由地做任何事情,因为,设计是你的,如果我想更喜欢多个面板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM