views:

256

answers:

2

I have Java application which adds JTextFields @ runtime to JPanel. Basically user clicks a button and new JTextField is added, clicks again added again...

Each new JTextField is directly below the previous one. Obviously I run out of space pretty soon so I'm trying to use JScrollPane and thats where the hell begins, because it just doesnt work no matter what I try.

  1. Right click on JPanel and Enclose in Scroll Pane. Didnt work.
  2. After reading some examples I realized I must have JPanel as an argument for JScrollPane constructor. Which I did via right clicking on ScrollPane and CustomizeCode. Because apparently auto-generated code is protected in NetBeans and I cannot just change all those declarations, etc. manually. Still doesnt work.
  3. I did try to set PreferedSize to null for JPanel and/or JScrollPane, didnt help.
  4. JScrollPane is a child of lets call it TabJPanel (which in turn is a tab of TabbedPane). I tried to mess with their relationships, basically trying every possible way of parentship between JFrame, JPanel(holding textfields), TabJPanel and JScrollPane, but nothing worked.
  5. I also made VerticalScrollBar "always visible" just in a case. So I see the scrollbar, it's just that populating that JPanel with JTextFields does not affect it.
  6. When there are too many JTextFields I they go "below" the bottom border of JPanel and I cannot see them anymore.

Code for adding new JTextFields is like this, in a case it's relevant.

JTextField newField = new JTextField( columns );
Rectangle coordinates = previousTextField.getBounds();
newField.setBounds(coordinates.x , coordinates.y + 50, coordinates.width, coordinates.height);

JPanel.add(newField);
JPanel.revalidate();
JPanel.repaint();

Sorry for a long post I'm just trying to provide as much info as possible, because being newbie I dont know whats exactly relevant and whats not. Thanks in advance :)

A: 

An option you have is to utilize a LayoutManager, instead of setting the bounds directly on the components. To test this, a simple single column GridLayout with the alignment set to vertical should prove the concept.

panel.setLayout(new GridLayout(0,1));

zero in the rows param allows for rows to be added to the layout as needed.

akf
+1  A: 

As there is another answer now, I'm adding my suggestion too.

This sounds exactly like a problem to use a JTable with a single column. JList is not yet editable (and might never be).

JTable would handle the layout problems for you, and you can easily access the values via the table.

Use your own TableModel (a simple Vector should be sufficient in your case), and add values to it.

Peter Lang
Thanks a lot, actually JTable with editable content fits my purpose way better than having lots of TextFields :)
Sejanus