The Swing updates the UI related changes only once using the Event Dispatch
Thread (EDT). The method
sp.getVerticalScrollBar().setValue(10); Does not update the UI. It is simply setting the value at 10. hence it is done immediately.
The second method that add the text to the screen willbring the Scroll Pane down but this will not be done immediately. It will be done on the EDT.
Hence when you run your code it will always run the setValue() method first and the setText() method later. Thus you will not see the effect of setValue().
The Solution would be to use SwingUtilities.invokeLater(). I have modified your code a little to make it more neater.
Hope it help!!!
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Tester extends JFrame {
private static final
String text = "1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n";
private JPanel contentPane;
private Box box;
private JScrollPane sp;
private JTextArea ta;
private JCheckBox cb1;
private JCheckBox cb2;
public Tester() {
super("Tester");
this.contentPane = (JPanel )this.getContentPane();
this.initComponents();
this.placeComponents();
this.setSize(300,200);
// this.setExtendedState(MAXIMIZED_BOTH);
this.setVisible(true);
// add listeners
this.addWindowListener(new FrameListener());
cb1.addItemListener(new Cb1Listener());
cb2.addItemListener(new Cb2Listener());
}
private void initComponents(){
ta = new JTextArea(text,5,2);
sp = new JScrollPane(ta,
ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
box = Box.createVerticalBox();
cb1 = new JCheckBox("set scroll 10",false);
cb2 = new JCheckBox("reload txt area and set scroll 10",false);
}
private void placeComponents(){
box.add(cb1);
box.add(cb2);
contentPane.add(sp, BorderLayout.CENTER);
contentPane.add(box, BorderLayout.EAST);
}
private class FrameListener extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
private class Cb1Listener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
sp.getVerticalScrollBar().setValue(10);
}
}
private class Cb2Listener implements ItemListener {
public void itemStateChanged(ItemEvent e) {
final Runnable run2 = new Runnable(){
public void run(){
sp.getVerticalScrollBar().setValue(10);
}
};
Runnable run1 = new Runnable(){
public void run(){
ta.setText(ta.getText());
SwingUtilities.invokeLater(run2);
}
};
SwingUtilities.invokeLater(run1);
}
}
public static void main(String[] args) {
Tester a = new Tester();
}
}