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