Hi,

I am messed up with jscrollbar in my applcation.I have a jtextarea with jscrollpane in my application. Whenever the text in the textarea fills up completely , i want the scrollbar to scroll down. As soon as new text is added to the textarea , the scrollbar should move down. I tried everything(view port etc,) but ended up with no luck..

Any idea of how to set the jscrollbar automatically ..

Thanks in advance

Recommended Answers

All 4 Replies

Maybe this can come in handy:

import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class view extends JFrame{
    private JTextArea tx = new JTextArea();
    private JScrollPane scroll = new JScrollPane(tx);

    public view(){
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        tx.setEditable(false);
        JPanel but = new JPanel (new GridLayout(2, 2));
        but.add(new JButton(new AbstractAction("Add text") {
            public void actionPerformed(ActionEvent e) { 
                for (int i=0;i<200;i++)
                    tx.append("Line["+Integer.toString(i)+"]: Hello World.\n");}}));
        but.add(new JButton(new AbstractAction("Clear area") {
            public void actionPerformed(ActionEvent e) {tx.setText("");}}));
        JPanel main = new JPanel (new GridLayout(1, 1));
        main.add(but);
        main.add(scroll);
        add(main);
    }

    public static void main(String arg[]){
        view v = new view();
        v.pack();
        v.setVisible(true);
    }
}

You'll probably have to resize the frame when it loads, but you'll see that the scroll pane works fine when adding text.

I want to add jscrollbar in my project and this is the same problem with me.

harinath_2007 wrote Whenever the text in the textarea fills up completely , i want the scrollbar to scroll down.

there are two ways:

1st. way

JTextArea textArea = new JTextArea();
DefaultCaret caret = (DefaultCaret)textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

2nd. way

  • get the JScrollBar from JScrollPane as local variable,
  • add DocumentListener to JTextArea
  • from proper Document event to call max value for JScrollbar

after

Quoted Text Here
there are two ways:
TextArea textArea = new JTextArea();
DefaultCaret caret = (DefaultCaret)textArea.getCaret();
caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);

Yes..that works..thanks a lot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.