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

前端 未结 2 1871
梦如初夏
梦如初夏 2021-01-15 19:51

I need to let users add more text fields to my JFrame so once the size of the frame has exceeded its original value a scroll pane would step in. Since I cannot add JScrollPa

相关标签:
2条回答
  • 2021-01-15 20:36

    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();
    
    0 讨论(0)
  • 2021-01-15 20:44

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

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

    0 讨论(0)
提交回复
热议问题