0

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();
      
   }
camickr
  • 321,443
  • 19
  • 166
  • 288
HappyJoy
  • 13
  • 6
  • A [mre] code post would be great here since it would give us code to start from. Please read the link. Having said that, I'd use a JList and not a bunch of JTextFields to display the 5 lines of text. Also, we currently can't see key code, including the layout managers being used. Also, ***never*** set the preferred size of a Swing text component. Ever. – Hovercraft Full Of Eels Jun 18 '21 at 01:25
  • Thank you for the feedback; sorry if my post was ambiguous or hard to understand. – HappyJoy Jun 18 '21 at 01:32
  • Thanks for the reply. The problem is it is hard to discern the underlying cause of the problem since we don't have code that we can compile and run that reproduces it for us, and in fact, you're showing us just small snippets of uncompilable code. We don't want the entire program as it is likely too large to ask volunteers to pour over, and likely contains much code that is not relevant to the issue at hand. Instead, best if you could provide code (as code-formatted text) that is small, but compiles, runs and demonstrates the problem for us, a [mre]. Please read the link as it will explain. – Hovercraft Full Of Eels Jun 18 '21 at 01:35
  • Thank you @HovercraftFullOfEels for your suggestion to use JList! Now my program works as I need it to :) Thank you – HappyJoy Jun 18 '21 at 01:57

1 Answers1

1

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.

camickr
  • 321,443
  • 19
  • 166
  • 288