Reputation: 11
I have been given a very specific requirement on how to display a list of messages. Each message can be up to 3200 characters long. For this particular display of the messages, only the first two lines of each are to be displayed, showing whatever fits of the message with the original format intact (tabs, spaces, newlines). The messages are to be contained in a JInternalFrame. When the user drags a side of the frame to increase or decrease its width, the visible text of a message is supposed to increase or decrease along with the frame, no horizontal scroll bar is desired.
I was able to get the desired behaviour with the text increasing/decreasing with the width of the frame using the following:
JTextArea ta = new JTextArea();
ta.setLineWrap(true);
ta.setWrapStyleWord(true);
ta.setRows(2);
ta.setEditable(false);
ta.setOpaque(false);
ta.setText(longString());
ta.setAlignmentY(TOP_ALIGNMENT);
JScrollPane scrollPane = new JScrollPane(ta);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_NEVER);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
A list of scrollPanes are added to a JScrollPane with a vertical scroll bar but no horizontal scroll bar in the JInternalFrame.
The problem I am having is that the text is resting on the bottom of the JTextArea, so the user sees the last two lines of the message, not the first two lines. It appears to be possible to set the horizontal alignment, but not the vertical alignment. Is there some way to get the automatically expanding/contracting text with text alignment at the top?
Upvotes: 1
Views: 5352
Reputation: 324098
After loading text into the text area you can use:
textArea.setCaretPosition(0);
Upvotes: 1
Reputation: 25954
This is something that's bugged me in the past as well. It has to do with how JTextComponents interact with JScrollPanes - specifically, there is a (invisible, when non-editable) Caret that ends up at the end of your JTextComponent. When the viewport tries to figure out what it should be viewing, it looks at the caret.
So, tell the JTextArea not to move the caret during your initialization block:
DefaultCaret c = new DefaultCaret();
c.setUpdatePolicy( DefaultCaret.NEVER_UPDATE );
ta.setCaret( c );
Upvotes: 1