1

I have a JScrollPane with JPanel on it. I have also many different components on JPanel (for example Labels, JTextFields, JTextAreas). These components are added programmatically (at runtime, on the user request). JPanel uses SpringLayout. The program calculates preferred size of JPanel after adding components, because scrolling doesn't function properly without calculating. Adding components and calculating preferred size are part of my prepareGui() method. The data displayed on components are periodically refreshed (in my refreshData() method, which is invoked by listener).

My problem: after refreshing, scroll bar always sets to fixed position (I don't know why). I want the scroll bar to stay in old position after refreshing.

I tried to find a place, where the scroll bar moves. I checked some values at the start and at the end of refreshData() method, but they was the same (they didn't change inside of refreshData()):

scrollPane.getVisibleRect().getX()
scrollPane.getVisibleRect().getY()
scrollPane.getVisibleRect().getWidth()
scrollPane.getVisibleRect().getHeight()
panel.getVisibleRect().getX()
panel.getVisibleRect().getY()
panel.getVisibleRect().getWidth()
panel.getVisibleRect().getHeight()
scrollPane.getHorizontalScrollBar().getX()
scrollPane.getHorizontalScrollBar().getY()
scrollPane.getHorizontalScrollBar().getWidth()
scrollPane.getHorizontalScrollBar().getHeight()
scrollPane.getHorizontalScrollBar().getValue()
scrollPane.getVerticalScrollBar().getX()
scrollPane.getVerticalScrollBar().getY()
scrollPane.getVerticalScrollBar().getWidth()
scrollPane.getVerticalScrollBar().getHeight()
scrollPane.getVerticalScrollBar().getValue()

Changing of layout manager didn't take effect.

I noticed one thing (I don't know if it has any meaning). When I set only preferred size (in prepareGui()), the scrollbar moves to the end. When I set also size, the scrollbar moves to strange, fixed position.

How can I prevent this? The scroll bar should keep it's current position.

Anad
  • 848
  • 7
  • 8

1 Answers1

1

I finally found the answer here: https://stackoverflow.com/a/5230477/5694159 (thanks to Johan M) in the topic about JTextArea instead of JPanel. When the refreshData() is calling in separate thread it works good.

I hope this question and answer will help someone.

Community
  • 1
  • 1
Anad
  • 848
  • 7
  • 8