BoxLayout doesn't work

Hello everyone. I need to create a window that will automatically add elements under each other (test, questions will be read from the file), it should also scroll. The BoxLayout with which the problem occurred is completely suitable for this. It does not place the elements under each other, nor do scroll bars appear. Experts, please tell me what I'm doing wrong?

P.S. fixed the scroll jamb.

package frames;

import javax.swing.*;
import java.awt.*;

public class Test1Frame extends JFrame {
    private JPanel test1Panel = new JPanel();
    private JScrollPane scrollPane = new JScrollPane(test1Panel);

    public Test1Frame(){
        super("Тест 1");
        setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
        setSize(800, 600);
        setResizable(false);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
        getContentPane().add(scrollPane);
        setPreferredSize(new Dimension(800, 600));
        setLocationRelativeTo(null);
        setVisible(true);
        runTest1();
    }

    private void runTest1(){
        test1Panel.add(new JLabel("1123123123123123"));
        for(int i = 0; i < 100; i++)
            test1Panel.add(new JButton("123123123123123123"));

    }
}
Author: Mr Krot, 2018-07-28

1 answers

  1. Set the panel's BoxLayout:

    test1Panel.setLayout(new BoxLayout(test1Panel, BoxLayout.Y_AXIS));
    

Instead of:

    setLayout(new BoxLayout(this.getContentPane(), BoxLayout.Y_AXIS));
  1. Call

    runTest1();
    

    Before:

    setVisible(true);  
    

Like this:

    runTest1();
    setVisible(true);
 0
Author: ezhov_da, 2018-07-28 16:25:45