Page 1 of 1

JScrollPane

PostPosted: Mon May 11, 2009 2:38 pm
by JesusFreak84
Stupid bug in a Java project--my final project, actually.

So I'm reading schtuff from an Access database, and the program itself is basically a shopping cart. Someone clicks an item in a list box, and a JTextArea, affixed to a JScrollPane, displays the name, price, description, etc. Problem is, when I select an item, the scroll bar jumps to midway in its track or lower, it won't just hover and chill at the top. The API documentation and Java tutorials haven't helped, and the prof has no clue either (though that's a perpetual state for this adjunct lady.)

Any Java code monkeys here have any ideas on how to get the behavior I want out of this infernal Swing component?

PostPosted: Mon May 11, 2009 5:40 pm
by Midori
Can you, after loading the content into the textarea, tell the scrollbar to jump to the top, with something like setCaretPosition? It seems like a hack, but it may be the easiest way.

PostPosted: Mon May 11, 2009 6:07 pm
by JesusFreak84
There's no such method in the API. :(

PostPosted: Mon May 11, 2009 6:48 pm
by Midori
I dunno, I was just looking at this page: http://codingclues.eu/2008/automatically-scrolling-down-in-a-jtextarea/

I would probably be more help if I actually knew Java. :P

Hm... Actually, I just looked at the JTextArea API on this page: http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JTextArea.html
and it says that it inherits a setCaretPosition method from JTextComponent: [url]http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/text/JTextComponent.html#setCaretPosition%28int%29[/url]

It's weird that it's a method on the textarea instead of the scrollbar though.

PostPosted: Tue May 12, 2009 3:52 am
by Warrior4Christ
UI elements do sometimes/often have odd behaviour that requires hacks to fix...

I have had this issue before, but I wanted it to stay scrolled to the bottom.
Use JTextArea.setCaretPosition(0), as Midori suggested.
What property are you altering on the JTextArea to make it do that?

PostPosted: Thu May 14, 2009 4:18 pm
by JesusFreak84
Turned out the reason I wasn't seeing .setCaretPosition(0) in the API was because it's a method of JTextArea's superclass, JTextComponent. I was looking in the JTextArea and JScrollPane APIs and that was it.

Danke, peoples! Worked great! ^_^