JTextArea AutoScroll Down Problem
843805Jan 17 2006 — edited Sep 27 2007Please help me.
I have a problem with autoscroll down in JTextArea. If I want to enter lines in JTextArea with for loop, auto scroll down do not show each last entered line. It shows last line when a for lop has finished. I want to scroll down after each iteration of for loop.
Here is complitly Java code which describes my problem.
When the button 'Add to Area' is clicked, each new line is added one after one, but when the lines exceeded visible area of JTextArea, it continues to add new lines, but scroll bar do not show last entered line. It positioned to the bottom after for loop finished.
I want to automaticly move scroll bar down for each new line which is entered.
Please help me.
Thanks to all
import javax.swing.JApplet;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import java.awt.Rectangle;
import java.awt.Font;
public class TextAreaProblem extends JApplet {
private javax.swing.JPanel jContentPane = null;
private JScrollPane jScrollPane = null;
private JTextArea jTextArea = null;
private JButton jButton = null;
public TextAreaProblem() {
super();
init();
}
public void init() {
this.setSize(300,400);
this.setContentPane(getJContentPane());
}
private javax.swing.JPanel getJContentPane() {
if(jContentPane == null) {
jContentPane = new javax.swing.JPanel();
jContentPane.setLayout(null);
jContentPane.add(getJScrollPane(), null);
jContentPane.add(getJButton(), null);
}
return jContentPane;
}
private JScrollPane getJScrollPane() {
if (jScrollPane == null) {
jScrollPane = new JScrollPane(getJTextArea());
jScrollPane.setBounds(50, 50, 190, 200);
jScrollPane.setVerticalScrollBarPolicy(javax.swing.JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
}
return jScrollPane;
}
private JTextArea getJTextArea() {
if (jTextArea == null) {
jTextArea = new JTextArea();
jTextArea.setEditable(false);
jTextArea.setFont(new Font("Arial", Font.BOLD, 12));
}
return jTextArea;
}
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton();
jButton.setBounds(50, 300, 120, 30);
jButton.setText("Add To Area");
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
for (int i = 1; i <= 20; i++) {
String str = "I = " + Integer.toString(i) + "\n";
addStringToTextArea(jTextArea, str);
}
}
});
}
return jButton;
}
private void addStringToTextArea(JTextArea ta, String str) {
try {
ta.append(str);
Rectangle rect = ta.getBounds();
ta.paintImmediately(rect);
Thread.sleep(200);
}
catch (InterruptedException ex) {}
}
}