Stop JScrollPane Scrolling If Knob Is Not At Bottom

My problem appears quite simple. I have a non-editable JTextArea in a JScrollPane. When text is added to the text area I want the vertical JScrollBar to autoscroll only if the knob is at the bottom of the track. If the user has scrolled up (e.g. to see a previous message) then the scroll bar should respect that and not change the position of the knob until the user moves the knob back to the bottom of the track. I've done quite a bit of searching for an answer and the following is the only one I've found that works, but I don't want to use it unless I absolutely have to because it just seems so wrong:
          AbstractDocument doc = (AbstractDocument) messageArea.getDocument();
           DocumentListener[] listeners = doc.getDocumentListeners();
           for (DocumentListener documentListener : listeners) {
              if (documentListener.getClass().getName().equals("javax.swing.text.DefaultCaret$Handler")) {
                 doc.removeDocumentListener(documentListener);
           }}Can someone please put me out of my misery and tell me the proper way to stop my JScrollBar from scrolling if the knob is at the bottom of the track? I would greatly appreciate it. Thanks.

camickr's [_Text Area Scrolling_|http://tips4java.wordpress.com/2008/10/22/text-area-scrolling/] may point you in the right direction.
db
edit Yup, with a little tweakingimport java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.*;
import javax.swing.text.DefaultCaret;
public class ScrollControl {
   JTextArea textArea;
   JScrollBar scrollBar;
   DefaultCaret caret;
   BoundedRangeModel model;
   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
            new ScrollControl().makeUI();
   public void makeUI() {
      textArea = new JTextArea(20, 30);
      textArea.setWrapStyleWord(true);
      textArea.setLineWrap(true);
      caret = (DefaultCaret) textArea.getCaret();
      JScrollPane scrollPane = new JScrollPane(textArea);
      scrollBar = scrollPane.getVerticalScrollBar();
      model = scrollBar.getModel();
      scrollBar.addAdjustmentListener(new AdjustmentListener() {
         public void adjustmentValueChanged(AdjustmentEvent e) {
            if (model.getValue() == model.getMaximum() - model.getExtent()) {
               caret.setDot(textArea.getText().length());
               caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
            } else {
               caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE);
      JButton button = new JButton("Click");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            for (int i = 0; i < 10; i++) {
               textArea.append("The quick brown fox jumps over the lazy dog. ");
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(400, 400);
      frame.add(scrollPane, BorderLayout.CENTER);
      frame.add(button, BorderLayout.SOUTH);
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
}Edited by: DarrylBurke

Similar Messages

  • JScrollPane  - scroll bar not visible

    I'm writing a graphical chat application where the user presses buttons to insert images into their message. The buttons reside in a JPanel with a GridLayout. As i have more buttons than can be physically seen on the screen I'm trying to use a JScrollPane encapsulated in the JPanel so that the user can scroll down the button list to select appropriate symbols. The problem i'm having is that the scroll bars do not appear so the user can only use symbols which are visible. Here is the code for what i'm trying to acheive.
    buttonPanel.setLayout(new GridLayout(9,3));
    buttonPanel.add(Button1);
    buttonPanel.add(Button2);
    buttonPanel.add(Button3);
    buttonPanel.add(Button4);
    .....etc to around Button100
    buttonHolder.add(new JScrollPane());
    buttonHolder.setPreferredSize(new Dimension(400,400));
    buttonHolder.setMaximumSize(new Dimension(400,400));I think I'm missing something from the add JScrollPane bit but I'm not sure what exactly!
    PLEASE HELP - this is for my third year dissertation and is the last bit I need to do before it is finished.

    First, you need to add your panel to the JScrollPane object. Then you add the JScrollPane object to the frame, not the panel itself.
    As for setting the scrollbars of the JScrollPane, you could try setVerticalScrollbarPolicy() and setHorzontalScrollbarPolicy().

  • Stop JScrollPane from scrolling

    Hello, I am trying to improve a special editor i have written. Now I tried to add line numbering to it and got stuck. Here's what I did:
    I have a JScrollPane that contains a JPanel. This JPanel has a BorderLayout and contains a JTextPane (where the editable text is) in the CENTER and a JTextArea (containing the line numbers) in the WEST.
    Everytime the text is edited, I count the lines and update the JTextArea so that the right amount of line numbers is shown. But here's the problem: Everytime I update the line numbers, the JScrollPane scrolls down to the very bottom, so in some cases the caret gets hidden (which is very annoying).
    Can someone tell me how I can tell the JScrollPane (or whoever else is to blame for this) not to scroll when I update the line number JTextArea? Is there an easy way to achieve this?
    Thanks in advance

    Another way to do this:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.text.rtf.*;
    class Test extends JFrame
    public Test()
    super("Test");
    JEditorPane edit = new JEditorPane();
    edit.setEditorKit(new MyRTFEditorKit());
    edit.setEditable(true);
    JScrollPane scroll=new JScrollPane(edit);
    getContentPane().add(scroll);
    setSize(300,300);
    setVisible(true);
    public static void main(String a[])
    new Test();
    class MyRTFEditorKit extends RTFEditorKit
    public ViewFactory getViewFactory()
    return new MyRTFViewFactory();
    class MyRTFViewFactory implements ViewFactory
    public View create(Element elem)
    String kind = elem.getName();
    if (kind != null)
    if (kind.equals(AbstractDocument.ContentElementName)) {
    return new LabelView(elem);
    } else if (kind.equals(AbstractDocument.ParagraphElementName)) {
    // return new ParagraphView(elem);
    return new MyParagraphView(elem);
    } else if (kind.equals(AbstractDocument.SectionElementName)) {
    // return new BoxView(elem, View.Y_AXIS);
    return new MySectionView(elem, View.Y_AXIS);
    } else if (kind.equals(StyleConstants.ComponentElementName)) {
    return new ComponentView(elem);
    } else if (kind.equals(StyleConstants.IconElementName)) {
    return new IconView(elem);
    // default to text display
    return new LabelView(elem);
    class MySectionView extends BoxView {
    public MySectionView(Element e, int axis)
    super(e,axis);
    public void paintChild(Graphics g,Rectangle r,int n) {
    if (n>0) {
    MyParagraphView child=(MyParagraphView)this.getView(n-1);
    int shift=child.shift+child.childCount;
    MyParagraphView current=(MyParagraphView)this.getView(n);
    current.shift=shift;
    super.paintChild(g,r,n);
    class MyParagraphView extends javax.swing.text.ParagraphView
    public int childCount;
    public int shift=0;
    public MyParagraphView(Element e)
    super(e);
    short top=0;
    short left=20;
    short bottom=0;
    short right=0;
    this.setInsets(top,left,bottom,right);
    public void paint(Graphics g, Shape a)
    childCount=this.getViewCount();
    super.paint (g,a);
    int rowCountInThisParagraph=this.getViewCount();
    System.err.println(rowCountInThisParagraph);
    public void paintChild(Graphics g,Rectangle r,int n) {
    super.paintChild(g,r,n);
    g.drawString(Integer.toString(shift+n+1),r.x-20,r.y+r.height-3);

  • When using safari, my screen will suddenly scroll all the way to the bottom and will not resound to any commands.  This affects all running programs.  How do I stop this?

    When I am on the internet, my screen will suddenly scroll all the way to the bottom and will not respond to any commands.  All of the other programs are then affected the same way and you cannot even use the commands at the top of the screen becayse they all scroll to the bottom.  After a while, the screen resets by itself.  Help.

    It sounds like a problem wih the backlight inverter. Usually they just go, instead of on and off.
    In a dark room hold a flashlight on the display when it blacks out. If you can see the items on the desktop, it's probably the backlight.

  • JScrollPane Scroll Position

    Tried posting this in the newbie section with no luck....
    I created a class extending a JScrollPane that encompasses a JTextPane. The method below appends some text to the current JTextPane with a certain color (this part works fine). What I am also trying to do is force the JScrollPane to keep focus at the bottom after the append if it was there before the append. Now I am running into trouble.
    The code can determine fine if the scroll pane is at the end, but after the append, it sometimes prematurely puts the pane at the end again; i.e. the method is telling the scroll pane to go to the end before the text pane and/or scroll pane have finished updating their size. Thus, the scroll pane is moved to the bottom, then the text and scroll panes resize, and the scroll pane is no longer at the bottom.
    It seems that this problem occurs when the text appended is multiple lines, in which case it appears that the panes are resized multiple times- the scroll bar is positioned correctly after the first resize, but subsequent resizings sometimes occur after I reposition the scroll bar to the current "end" (which then changes).
    I've tried validating both panes to force them to update before repositioning the scroll bar, but this does not seem to stop the problem (although it may help).
    Does anyone know how to correct this problem? I'm still guessing that something (perhaps the doc?) is not fully updated by the time I reposition the scroll bar. If this is the problem, any suggestions on how to force the document to be updated before playing with these GUI panes? If possible, I prefer not to use a timer or sleep a thread to wait for this updating.
    Of course, if you know of existing methods/settings that help with this, please tell. I didn't manage to find anything in the API's that gave me what I want, but I've been known to overlook things from time to time ;)
    Again, this is a method in a class extending JScrollPane.
    textPane is the JTextPane embedded in the scroll pane.
    doc is the JTextPane document.
    public synchronized void append(String appendString, Color textColor)
         JScrollBar scrollBar;
         BoundedRangeModel rangeModel;
         boolean isMaxed;
         scrollBar = this.getVerticalScrollBar();
         rangeModel = scrollBar.getModel();
         isMaxed = ((rangeModel.getValue() + rangeModel.getExtent())
                             == rangeModel.getMaximum());
              // check if the scroll bar is at the bottom
         SimpleAttributeSet textAttributes = new SimpleAttributeSet();
         StyleConstants.setForeground(textAttributes, textColor);
         try
              doc.insertString(doc.getLength(), appendString, textAttributes);
              // append the formatted string to the document
         catch(BadLocationException ex)
              System.out.println("Error writing to the text pane");
         if (isMaxed)
              textPane.validate();     //force the text pane to validate
              this.validate();    //force the scroll pane to update
              scrollBar.setValue(rangeModel.getMaximum() - rangeModel.getExtent());
              // The above line is sometimes called before the text and scroll panes
              // have finished updating.  The maximum and extent of the scroll bar
              // depend on the size of the document.

    You are correct in your observation that the size of the JScrollPane is incorrectly reflected for the size of your newly appended document. I spent some time on this bug and eventually came up with the following solution:
    textPane.addComponentListener( new ComponentListener(){
    public void componentHidden(ComponentEvent e)
    public void componentMoved(ComponentEvent e)
    public void componentResized(ComponentEvent e)
    JViewport vp = scrollPane.getViewport();
    incoming.revalidate();
    Rectangle visRect = vp.getViewRect();
    Dimension viewDim = vp.getViewSize();
    Rectangle rect = new Rectangle( 0, (int)(viewDim.getHeight() - visRect.getHeight()),
    (int)visRect.getWidth(), (int)visRect.getHeight() );
    vp.scrollRectToVisible( rect );
    public void componentShown(ComponentEvent e )
    This solution also has the side benefit of scrolling to the bottom when the JTextPane is resized by the user.

  • At work with the text at allocation by the cursor of the big fragment of page it is necessary to shift all time it downwards, "against the stop", but the page automatically does not start to rise upwards as occurs in other browsers. I ask the help!

    After transition on Windows 7 there was a problem with Firefox. At work with the text at allocation by the cursor of the big fragment of page it is necessary to shift all time it downwards, "against the stop", but the page automatically does not start to rise upwards as it was earlier and as occurs in other browsers. It is necessary to press other hand a key "downwards" that is the extremely inconvenient. Reinstallation on earlier version (8.0) earlier irreproachably working, has given nothing. I ask the help

    You need to enable the Add-ons bar (Firefox > Options or View > Toolbars; Ctrl+/) or the Find bar (Ctrl+F) to make Firefox scroll the page while selecting text.

  • Music stop after scrolling more than 2 pages in Pages (ver:1.5)

    Music stop after scrolling more than 2 pages in Pages.

    Hi
    Try this:
    &SFSY-PAGE& of &SFSY-JOBPAGES(3ZC)&
    U can find the explanation in note [779492|https://websmp230.sap-ag.de/sap%28bD1lbiZjPTAwMQ==%29/bc/bsp/spn/sapnotes/index2.htm?numm=779492]
    Max

  • I just did a software update that was apparently for iPhoto. When I try to open iPhoto it stops at "step 5" and will not go further. what do I do?

    I just did a software update that was apparently for iPhoto. When I try to open iPhoto it stops at "step 5" and will not go further. what do I do?

    Option 1
    Back Up and try rebuild the library: hold down the command and option (or alt) keys while launching iPhoto. Use the resulting dialogue to rebuild. Choose to Rebuild iPhoto Library Database from automatic backup.
    If that fails:
    Option 2
    Download iPhoto Library Manager and use its rebuild function. This will create a new library based on data in the albumdata.xml file. Not everything will be brought over - no slideshows, books or calendars, for instance - but it should get all your albums and keywords back.
    Because this process creates an entirely new library and leaves your old one untouched, it is non-destructive, and if you're not happy with the results you can simply return to your old one. .
    Regards
    TD

  • How can I animate my sprite to run on scroll and stop when scrolling stops?

    I appreciate everyones help so far.
    I want my illustration of a man to "walk" through my composition as the user scrolls through it.
    I have a sprite created and have made it loop. What sort of code do I need to write to get it to move only on scroll and stop off scroll?
    Thank you guys so much!
    Johnathan

    Hi,
    Thank you for your post.
    Please check the following tutorials for scrolling effects in edge animate.
    http://www.heathrowe.com/adobe-edge-animate-simple-scrollbar-symbols/
    http://www.adobe.com/inspire/2014/01/parallax-edge-animate.html
    Regards,
    Devendra

  • My 160GB ipod classic stopped whilst playing music and will not turn back on despite having almost a full battery. I have tried connecting to itunes and a docking station but will not turn on at all - HELP?!

    My 160GB ipod classic stopped whilst playing music and will not turn back on despite having almost a full battery. I have tried connecting to itunes and a docking station but will not turn on at all - HELP?!
    I've had this from new for 2 years, the battery life is excellent and lasts for days so I know it's not a power issue as it was fully charged that morning. No signs of connection in itunes, it's not showing as a connected device.
    Can anyone please help?

    Hi gscoops,
    Welcome to Apple Support Communities.
    You may find the steps in our iPod Troubleshooting Assistant helpful:
    http://www.apple.com/support/ipod/five_rs/classic/
    Best,
    Jeremy

  • Hi!My 6 month old MBP 13" has suddenly stop charging.Mac is working,but not charging

    Hi!My 6 month old MBP 13" has suddenly stop charging.Mac is working,but not charging

    Troubleshooting MagSafe adapters  http://support.apple.com/kb/ts1713
    If you need to pursue further you can do it on-line,  start here
    https://selfsolve.apple.com/agreementWarrantyDynamic.do

  • Macbook Pro retina display 13 inch stopped charging. Charger LED also not on while plugged in. The battery fully drained off but the system can detect the charger when it was switched on.

    Macbook Pro retina display 13 inch 2014 model stopped charging. Charger LED also not on while plugged in. The battery fully drained off so the system can not be started but the system can detect the charger when earlier it was switched on before draining off the charge. Charger type magsafe 60W.

    Once you have examined the power inlet on the computer for dirt, and made certain that the pins on the end of the MagSafe cord are free to move in and out to make contact, there is very little you can do yourself.
    You will need to visit your Apple Store (FREE with appointment) or your Apple-Authorized Service Provider (policy varies). They work on these all the time and have good expertise and lots of spare parts to try to determine the problem.

  • How can I stop auto update for the OS (not the apps)?

    Is there a way to stop the phone (mine is samsung note 3) from updating the OS (not the apps)? It works fine with the current version, and I have had/heard about issues with OS upgrades basically messing up the phone.

        srinik1, we want you to have the best wireless experience on your device. There's no way to restrict your device from receiving this update. You will continue to receive alerts to advise you to update the software on your device until you complete it. Should you have any issues with your device after updating, please feel free to reach out to us for assistance. We're here to help.
    LasinaH_VZW
    Follow us on Twitter @VZWSupport

  • Bookmark sidebar will not scroll and bookmarks will not open in Firefox 7 or 8

    Cannot get past Firefox 6 without probelms with Bookmarks sidebar. Sidebar will not scroll and folders will not open to reveal bookmark contents. Had this problem with Firefox 7 and again with Firefox 8. Would like to use latest version for security reasons, but it is useless to me if I can't access bookmarks

    Try:
    *http://kb.mozillazine.org/Corrupt_localstore.rdf
    Start Firefox in <u>[[Safe Mode]]</u> to check if one of the extensions or if hardware acceleration is causing the problem (switch to the DEFAULT theme: Firefox (Tools) > Add-ons > Appearance/Themes).
    *Don't make any changes on the Safe mode start window.
    *https://support.mozilla.com/kb/Safe+Mode

  • The "small ball" on the mouse allows me only to scroll to the top not to the bottom

    The "small ball" on the mouse allows me only to scroll to the top not to the bottom

    Crud builds up under the ball and prevents the rollers from operating properly.
    Turn it upside down and rub the ball vigorously with a microfiber cloth.
    Regards,
    Captfred

Maybe you are looking for