How to insert a String at the CaretPosition without moving the Caret?

I have a JTextPane wrapped by a JScrollPane. The JTextPane is where chatroom messages appear. When a message is appended at the end, it determines whether to scroll to the bottom based on some conditions (scroll to the bottom only if the user was already viewing somewhere near the bottom). That part is working fine.
Although the JTextPane is not editable, it allows the user to make selections using a mouse so that blocks of text can be copied from the chatroom. The default caret of JTextPane handles that for me.
But the problem comes when the caret position is at the end of the document when my program inserts a new message with the following code:
StyledDocument doc = textPane.getStyledDocument();
doc.insertString(doc.getLength(), message + "\n", null);The caret was at doc.getLength() to begin with, when the new message is inserted at the end, it "pushes" the caret to a new position. The caret movement is causing JScrollPane to scroll to where the caret is visible (the bottom), therefore interfering with my scrolling algorithm (see above).
So, when the caret is doc.getLength(), how do I insert a String at doc.getLength() with the caret staying at the original position?
In other words, how do I insert a String at the caret position without the caret being moved?
Note:
1) I don't want to use setCaretPosition() to set the caret to its original position, because calling this method will trigger a CaretEvent, thus causing the JScrollPane to scroll (to the caret) which is not what I want (see above).
2) I don't want to remove the CaretListener, cause then the JScrollPane won't scroll even when the user wants to make a multiple-page selection using the mouse (dragging the selection off screen).
3) I want to keep the Caret at the original position so that the user won't lose his/her selection when new messages appear (which can be quite frequent).

I keep forgetting how difficult it is to do such simple things in the text package. But it's not impossible! Here's a way to replace the relevant listeners, plus a sample implementation. If you know you'll never, ever delete any text from the JTextPane, you may not have to provide a replacement DocumentListener at all; this one just makes sure the caret isn't past the end of the document.
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.text.DefaultCaret;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
public class ChatCaret extends DefaultCaret
  private MyHandler newHandler;
  private PropertyChangeListener oldHandler;
  public void install(JTextComponent c)
    super.install(c);
    PropertyChangeListener[] pcls = c.getPropertyChangeListeners();
    for (int i = 0; i < pcls.length; i++)
      if (pcls.getClass().getName().equals(
"javax.swing.text.DefaultCaret$Handler"))
oldHandler = pcls[i];
newHandler = new MyHandler(oldHandler);
c.removePropertyChangeListener(oldHandler);
c.addPropertyChangeListener(newHandler);
break;
Document doc = c.getDocument();
if (doc != null)
doc.removeDocumentListener((DocumentListener)oldHandler);
doc.addDocumentListener(newHandler);
public void deinstall(JTextComponent c)
super.deinstall(c);
c.removePropertyChangeListener(newHandler);
Document doc = c.getDocument();
if (doc != null)
doc.removeDocumentListener(newHandler);
class MyHandler implements PropertyChangeListener, DocumentListener
private PropertyChangeListener oldHandler;
MyHandler(PropertyChangeListener oldHandler)
this.oldHandler = oldHandler;
public void propertyChange(PropertyChangeEvent evt)
Object oldValue = evt.getOldValue();
Object newValue = evt.getNewValue();
if ((oldValue instanceof Document) ||
(newValue instanceof Document))
setDot(0);
if (oldValue != null)
((Document)oldValue).removeDocumentListener(this);
if (newValue != null)
((Document)newValue).addDocumentListener(this);
else
oldHandler.propertyChange(evt);
public void removeUpdate(DocumentEvent evt)
int length = getComponent().getDocument().getLength();
if (length < getDot())
setDot(length);
public void insertUpdate(DocumentEvent evt) { }
public void changedUpdate(DocumentEvent evt) { }

Similar Messages

  • How to insert a string containing a single quote to the msql database? help

    how can i insert a string which contains a single quote in to database... anyone help
    Message was edited by:
    sijo_james

    Absolutely, Positively use a PreparedStatement. Do not use sqlEscape() function unless you have some overriding need (and I don't know what that could possibly be).
    There are 1000's of posts on the positive aspects of using a PreparedStatement rather than using a Statement. The two primary positive attributes of using a PreparedStatement are automatic escaping of Strings and a stronger security model for your application.

  • Using crop to change aspect ratio, but now is there a way to shift the footage without moving the cropped area?

    Hi guys!
    I'm new and not sure if this is the correct way to go about this. I am using the crop tool to achieve 2.35:1. But is there a way to transform my footage "beneath" the cropped area or do I always have to create a composition in AE and put a black bar layer on top? 
    Thanks in advance!

    I would create the black bars in the title designer and put that on the highest video track of your sequence.

  • How to insert some strings in a query with the clausule 'in' in a procedure

    Hello fellows.
    Do you know how to insert some strings in a query with the clausule 'in' in a procedure (with a variable)?.
    I tell us my problem with an example:
    I want to use this select but introducing a variable instead the 'value1', 'value2':
    select * from table1 where field1 in ('value1', 'value2');
    if I declare the variable var1 as:
    TC_VAR1 CONSTANT VARCHAR2(50) := '''value1'',''value2'''
    and I use it as:
    select * from table1 where field1 in (TC_VAR1);
    It doesn't work because Oracle takes TC_VAR1 as an all string. I think Oracle takes it as this:
    select * from table1 where field1 in ('value1, value2');
    If I use the data type TABLE, I don't know how to use well:
    TYPE varchar2_table IS TABLE OF VARCHAR2(10);
    tb_var varchar2_table;
    select * from table1 where field1 in (tb_var);->It returns an error and there ins't an method that it returns all values.
    A curious case is that if I have a sql script (for example script1.sh) with this query:
    select * fromt able1 where field1 in (&1)
    and I invoke this script as
    script1.sh "'''value1'',''value2'''". It works
    Can anybody helps me?.
    Thanks.

    Thanks to all. Really.
    First, sorry for my English. It's horrible. Thank to all for understand it (my English).
    I've resolved my problem with these links:
    ORA-22905: cannot access rows from a non-nested table item
    and
    http://stackoverflow.com/questions/896356/oracle-error-ora-22905-cannot-access-rows-from-a-non-nested-table-item
    At last, I have used someting like this:
    DECLARE
    number_table_tmp NUM_ARRAY:=NUM_ARRAY(410673, 414303, 414454, 413977, 414042, 414115, 413972, 414104, 414062);
    BEGIN
    FOR c1 IN (SELECT par_id, 1 acc_vdo_id FROM SIG_VIS_CAM
    WHERE par_id IN (SELECT * FROM TABLE(number_table_tmp))
    UNION ALL
    SELECT par_id, 2 acc_vdo_id FROM SIG_ACCAO a
    WHERE par_id IN (SELECT * FROM TABLE(number_table_tmp))) LOOP
    NULL;
    END LOOP;
    END;
    but first I had to create the type NUM_ARRAY like this:
    CREATE TYPE subjectid_tab AS TABLE OF NUMBER INDEX BY binary_integer;
    THANK YOU, GUYS. YOU ARE THE BESTS. ;-)
    Edited by: user12249099 on 08-sep-2011 7:37
    Edited by: user12249099 on 08-sep-2011 7:37

  • Am new at pages and cannot figure out how to insert a bullet where I want it in the text, not at the beginning of the paragraph.  Word was much easier for me

    Am new at this forum and also at pages and can't figure out how to insert a bullet where I want it in the text, not at the beginning of the paragraph.  I found word much easier to use.  Please help. Trying to do a resume.

    On a US keyboard it is Option + 8 (above the letters). •

  • When I insert a shape, how do I change the color without changing the texture?

    When I insert a shape, how do I change the color without changing the texture?

    Hi,
    you are working with a percentage width of your tables, for example:
    table width="123%
    td width="75%"
    td width="25%"
    So it is simply a arithmetic problem to get the proportional wide (means the ratio of % to cm) of your images, so that they do not break the frame. Certainly you could use (translated from German DW) "properties" and change the sizes there:
    Hans-G.

  • How do I clear list of items purchased without deleting the apps?

    How do I clear list of items purchased without deleting the apps? Also, is there away to attach photos from camera roll when replying or writing a new email?

    There is no way to remove items from the purchased list on the iPad.
    You can send a photo from the mail app by tapping and holding down in the body of the email and select - Insert Photo or Video - from the black options bar that will pop up.

  • I have all my music on an external media drive that has crashed. How can I get the music of my ipod touch back onto the comupter without loosing the music when it syncs?

    I have all my music on an external media drive that has crashed. How can I get the music of my ipod touch back onto the comupter without loosing the music when it syncs. in order to start rebuilding my music collection?

    You should be able to recover the media with the tips in  this post from forum regular Zevoneer but I'm not sure what the implications are for your application settings. You can probably transfer your purchases into a newly authorised library, backup the device, recover any other media using third party tools, then restore the device from the backup. That should switch the assocation of the device to the new library but it is not something I've personally tested.
    When you get it all working, make a backup!
    tt2

  • How can I change the password in the iBook donated to our nonprofit.  No password was given with the iBook?  We need to put in printer and other software.  Help, we can use the laptop without changing the password.

      How can we change the password in the iBook donated to our nonprofit?  No password was given with the iBook and every time we try to install items, the password window pops up.  We need to put in printer and other software.  Help! We can use the laptop without changing the password.

    If you did not get an OS X install-restore DVD with the computer you may need
    to buy one from somewhere, and you may be lucky to get a retail OS X 10.5.x
    version. The original grey-label install set of software and OS X it shipped with
    likely would be an older system than Leopard 10.5. Last versions of G4 Mac, &
    G5, shipped with a Tiger 10.4 system; so did early Intel-based Mac. Grey discs
    which accompanied other computer build models generally do not interchange.
    The last OS X version a PowerPC architecture can use, if supported, is 10.5.8.
    A PPC processor at 867MHz & faster should be able to run OS X 10.5 Leopard.
    {With the correct disc installer, you can use it to change a password and other
    things including re-install, and perform disk utility functions, etc.}
    There is a chance you may be able to get a white-label Replacement 10.4 DVD
    or Replacement 10.5 DVD from AppleCare or the online Apple Store (800myapple)
    from a Mac OS X system specialist; these have been available yet hard to get
    as not all persons involved with them seem to know if they still exist until someone
    is asking. These aren't retail stock, are special discs for computers who could use
    a system later than original old discs; these are complete install discs not for one
    specific series of Mac. Generally they'd work in supported PowerPC G4/G5; but
    do not replace specialized original install DVD, such as an early Intel mac requires.
    You'd need to have a serial number of the computer, and a method of payment
    when seeking some replacement system media from Applecare or Apple sales
    and these discs are not available in a retail store. The original Retail discs are
    labeled differently and shipped in a retail box with a big X on the front. Other
    sources for retail 10.4 Tiger or 10.5 Leopard may be online via amazon sellers
    or computer resellers who handle repaired Macs. Avoid mystery grey label ones
    that were intended to be sold and kept with their original computer kits.
    Good luck!

  • How do you move an Event Library without moving the physical media

    I've got a large library of media that needs to be organized, with new keywords.  I have multiple people on different computers attacking portions of the media all stored on a single raid, accessed via gigabit ethernet.  When the libraries are created on each computer, the media is kept in it's original place.  Because the drive is networked, FCP X won't let me place the Event Library on the drive, though I can access the media.  It will also not let me move or duplicate the libraries to the networked drive.  If I connect a drive locally, I can move, copy or duplicate the Event Library, but, here's the problem, instead of copying the alias' to the media, and keeping it like the original event library, it copies the full media into the new library, unnecessarily.
    Has anybody found how to copy the Copy, Move or Duplicate the Event Libraries without moving the actual media to the new Library?  I'd like to copy the new libraries to the networked drive where the media is stored and then relink the files.  Then I could merge each computers Library into a master library.
    Does that make sense to anybody?  There has to be a way to stop FCP X from unnecessarily copying the media.

    Not sure if this is what you're looking for but - Did you uncheck 'Copy files to Final Cut Events Folder' when importing into your project?

  • How do I move pictures off my phone without losing the pictures permanently?  Is there a way to keep the pictures in the cloud without them being on my device?

    How do I move pictures off my phone without losing the pictures permanently?  Is there a way to keep the pictures in the cloud without them being on my actual phone?  I'm concerned that the sync feature will remove the pictures from the cloud when they are deleted from my phone.
    Thanks for the help.

    Can I back up iPhoto to the cloud via some apple service (iCloud)
    No
    or do I need to use something else?  If so, any recommendations?
    An external hard disk:
    Most Simple Back Up:
    Drag the iPhoto Library from your Pictures Folder to another Disk. This will make a copy on that disk.
    Slightly more complex: Use an app that will do incremental back ups. This is a very good way to work. The first time you run the back up the app will make a complete copy of the Library. Thereafter it will update the back up with the changes you have made. That makes subsequent back ups much faster. Many of these apps also have scheduling capabilities: So set it up and it will do the back up automatically.
    Example of such apps: Chronosync - but there are many others. Search on MacUpdate or the App Store

  • How do I move booksmark to another machine without replacing the bookmarks on the new machine, i.e combine a number of bookmark files

    I'm setting up a laptop and want to have all the bookmarks from my desk machine to be moved there from different accounts, but in end up in one file so that I don't have to have loads of separate accounts.

    You need to combine all the links to one HTML file.
    You only need a file with Anchor links like this:
    <pre><nowiki>
    <a href="https://support.mozilla.com/en-US/questions/754997">How do I move booksmark to another machine without replacing the bookmarks on the new machine, i.e combine a number of bookmark files | Firefox Support Forum | Firefox Support</a></nowiki></pre>
    If you export bookmarks to an HTML file then you create a copy of your bookmarks and you edit that copy and you do not affect the original bookmarks.
    See also [/questions/737050]

  • How to delete aggreagetd data in a cube without deleting the Aggregates?

    Hi Experts,
    How to delete aggreagetd data in a cube without deleting the Aggregates?
    Regards
    Alok Kashyap

    Hi,
    You can deactivate the aggregate. The data will be deleted but structure will remain.
    If you switch off the aggregates it wont be identified by the OLAP processor. report will fetch the data directly from the cube. Switching off the aggreagte won't delete any data,but temporarly the aggregate will not be availbale as if it is not built on the info cube. No reporting is not possible on swtiched off aggregates. The definition of the aggregate is not deleted.
    You can temporarily switch off an aggregate to check if you need to use it. An aggregate that is switched off is not used when a query is executed.This aggregate will be having data from the previous load's. If the aggregate is switched off means it wont be available for reporting but data can be rolled up into it.
    If u deactivate the aggregates the data will be deleted from the aggregates and the aggregate structure will remain the same.
    The system deletes all the data and database tables of an aggregate. The definition of the aggregate is not deleted.
    Later when you need those aggregate once again you have to create it from scratch.
    Hope this helps.
    Thanks,
    JituK

  • My friend synced a video to my ipod but it erased all my data on my ipod,but i cant figure out how to load my old libray back without deleting the movie. my friend cant tell me the password. How can I get my old library back without deleting the movie?

    My friend synced a video to my ipod but it earased all my data on my ipod,but I can't figure out how to load my old library back without deleting the movie. My friend shares a family account so she can't tell me the password. How can i get my old library back without deleting the movie?

    Linnwarner wrote:
    She does have the right because she bought the movie.
    Not true at all.
    You only buy the right to your own personal use.
    You do NOT have the right to distribute to others.
    This is illegal.  There is no doubt about it

  • How do i print from indesign (CS4) landscape without losing the edges.

    i'm a PC to MAC newbe. Also moved from CS2 toCS4.
    can't for the life of me figure out how to print from indesign in landscape layout without losing the left 2.5 inches of print. having the same trouble with #10 envelopes.
    your help would be appreciated!

    Usually this problem has to do with choosing the correct size and orientation of paper, both page size and print paper size.
    IOW, if you want to print to a #10 envelope, start a new document that is exactly the size of a #10 envelope. Then when you print it, choose a paper size that is exactly the size of a #10 envelope.
    What size page are you printing, and what paper size are you choosing when you print it?
    Ken

Maybe you are looking for

  • My reading list stopped syncing to my PC

    My reading list will not sync anymore on my PC in Safari. the last time it synced was Saturday, September 21, 2013, 12:36:00 AM. I have W7 64bit Professional. I updated my iphone to ios7 the day after it came out.

  • App Store problems again?

    I keep getting the 'Cannot connect to iTunes store' message.. I have a ipad2 wifi only model and have recently updated to the new iOS 6.1 update.. Is there a service outage like on the 25 of October? Any advice people??

  • XML to IDOC    -- How to configure.

    Hi I need some guidance on configuring our XI 2.0. Our scope is simple. We would like to read XML and output it to SAP as an IDOC. I would appreciate if some one can provide overview of steps to follow.

  • Problem Ordering a Book

    I click "order book". The "Order Book" page pops up. I'm not able to change the quantity from 0 to 1. The only available buttons are "cancel" and "set up account" I click "set up account" and it opens the "set up account" page. This allows me to sign

  • Best format for iMovie input: DV or AppleIntermetiateCodec

    I thought (and I think I read here several times) that the best input for iMovie, if you use a MiniDV camcorder, was to import the DV files into the app. Now I have read an article ( http://imovietricks.blogspot.com/ )where it is said that iMovie doe