I need to make my JPanel resize dynamically as new components are being added to it

不问归期 提交于 2019-12-01 13:03:39

I changed the Layout in your JPanel to GridLayout, so the Size of it is just handeld by the Layoutmanager depending on the components on the panel.

    JFrame f = new JFrame();
    f.setLayout(new BorderLayout());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JPanel p = new JPanel(new GridLayout(0, 5));
    JScrollPane jsp = new JScrollPane(p);

    jsp.setPreferredSize(new Dimension(300,300));
    jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);

    for (int i = 0; i < 100; i++) {
        JButton b = new JButton("Button " + i);
        p.add(b);
    }

    f.add(jsp, BorderLayout.CENTER);
    f.setLocation(300, 300);
    f.setVisible(true);
    f.pack();

Choose the Miglayout option under Layouts. i found this to be the easiest way

https://i.stack.imgur.com/XKHVu.png

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!