Skip to content
Advertisement

Problems removing and replacing components from JScrollPane [closed]

I am having problems changing JScrollPane components. I have an ArrayList named textFields from which I want to take elements and add to my scrollPane.

Can someone please help me? I cannot seem to remove the scrollPane’s elements or seem to add the other textfields from the ArrayList. Here is my method ::

private void resetJSPComponents()
   {
     
      scrollPane.removeAll();
      for(int a = 0; a < 5; a++)
      {   
        JTextField jTF = textFields.get(a); 
       scrollPane.add(jTF);  
      }
      
      scrollPane.revalidate();
      scrollPane.repaint();
      
   }

Advertisement

Answer

I know you have a better solution, but for the future when using a JScrollPane here is the answer to your original question.

Problems removing and replacing components from JScrollPane

  scrollPane.removeAll();
  for(int a = 0; a < 5; a++)
  {   
    JTextField jTF = textFields.get(a); 
   scrollPane.add(jTF);  
  }

Never remove/add components to the scrollpane. The scroll pane is a complicated component and contains many child components:

  1. horizontal/vertical scrollbars
  2. column/row headers
  3. a viewport

To change what is displayed in the scroll pane, you reset the component in the viewport.

So in your example you would:

  1. create a JPanel for all the child components
  2. add the text fields to this panel

Then you use:

scrollPane.setViewportView( panel );

Thats all. No need to use the removeAll() method or to revalidate() and repaint() the scroll pane.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement