1

I have a JPanel with a vertical BoxLayout, for one element i want to be able to use another BoxLayout which places elements horisontally. 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?

1 Answers1

3

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....

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.


Should i create another JPanel and put that inside the first 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.

Azad
  • 5,047
  • 20
  • 38