Reputation: 271
I am working with Java Swing and I have put a JTextArea in a JScrollBar. What I want is the scrollbar to follow the data. For a example i want to write in the JTextArea the output of a for(;;) so i can see the latest (newest) values. How could I do that?
EDIT: I have edited the question to be more specific.
Upvotes: 1
Views: 2642
Reputation: 168825
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class AutoScrollTextArea {
static String text = "Lorem ipsum dolor sit amet, "
+"consectetur adipiscing elit. "
+"Integer vestibulum metus id elit malesuada mattis. "
+"Aliquam non rutrum justo. Morbi eleifend nisi ut "
+"turpis commodo nec ultricies arcu vehicula. "
+"Donec varius neque at nunc pellentesque tincidunt. "
+"Phasellus sed ante ut tortor fermentum posuere sed "
+"sit amet tortor. Sed cursus magna a lacus mattis eleifend. "
+"Aliquam congue faucibus purus vel commodo. "
+"Fusce rutrum consectetur nibh nec facilisis. ";
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
JPanel gui = new JPanel(new BorderLayout(5,5));
final JTextArea textArea = new JTextArea(10,60);
textArea.setWrapStyleWord(true);
textArea.setLineWrap(true);
textArea.setEnabled(false);
gui.add(new JScrollPane(textArea), BorderLayout.CENTER);
JButton button = new JButton("Add Text");
button.addActionListener( new ActionListener(){
public void actionPerformed(ActionEvent ae) {
textArea.append(text);
textArea.append(System.getProperty("line.separator"));
textArea.append(System.getProperty("line.separator"));
}
} );
gui.add(button, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(null, gui);
}
};
SwingUtilities.invokeLater(r);
}
}
( It happens automatically ;)
Upvotes: 2
Reputation: 59660
IF you are using JTextArea in JScrollPane then following should work:
JTextArea area = new JTextArea();
area.setWrapStyleWord(true);
area.setLineWrap(true);
JScrollPane pane = new JScrollPane(area);
Upvotes: 1