I need to let users add more text fields to my JFrame so once the size of the containing frame being JPanel has exceeded its original value a scroll pane would step in. In order to be able to do this, I came up with an idea to put one JButton and upon hitting it a new TextField would show up (this was my original idea which doesn't necessarily mean I am right). The problem is, once I call the ActionListener class to add more TextFields and eventually stretch its containing panel, the program asks me to make the JPanel final which in turns doesn't allow for stretching of the panel. In other words, it appears to me that I'm just beating around the bush, please help me out put this together, below is a piece of my code:
public class Button {
public static void main(String[] args) {
JFrame f = new JFrame();
f.setLayout(new BorderLayout());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final 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);
JButton but = new JButton("Add");
f.add(but);
but.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int height=0;
JTextField jtx = new JTextField();
jtx.setSize(new Dimension(70,20));
jtx.setPreferredSize(new Dimension(70,20));
p.add(jtf);
height+=20;
p.setSize(new Dimension(300, height));
p.setPreferredSize(new Dimension(300, height));
}
});
f.add(jsp, BorderLayout.CENTER);
f.setLocation(300, 300);
f.setVisible(true);
f.pack();
}
}