Alternative text display in JTextPanel

Is it possible to do something in JTextPanel similar to emoticons in MSN Messenger. Where if you type something like =) a smiley icon replaces that text. Yet if you call getText() it will still return you the String "=)". Also, once the smiley icon is formed, if you press delete, it will delete the whole =) icon and not just the ")".

well, to be clean, the solution should use the DocumentFilter to make modifications to the document. Here's an updated version including a fix for the adjacent TextReferences bug you found. You can just as easily change it back to use a custom Document.
Your problem with the infinite loop should be fairly easy to solve. The problem is that the insert code executes from the same method (insertString) regardless of who's calling it. You should change your updateAttributes method to call "remove" on the text to replace instead of "replace". Then, use a custom "insertStringNoParse" method in your Document that simply bypasses the spawning of your Parser thread.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
* Created on November 18, 2005
* @author Jaspre
public class TextPaneTest extends JFrame {
    private JTextPane pane;
    private DefaultStyledDocument doc;
    public TextPaneTest() {
        super("test");
        setSize(300, 300);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        doc = new DefaultStyledDocument();
        doc.setDocumentFilter(new TextReferenceFilter());
        pane = new JTextPane(doc);
        pane.setText("this is a sentence without text references");
        pane.addCaretListener(new TextReferenceCaretHandler());
        JButton button = new JButton("Make Reference");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                makeReference();
        JScrollPane scr = new JScrollPane(pane);
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scr);
        getContentPane().add(button, BorderLayout.NORTH);
        setVisible(true);
    private TextReference getTextReference(int off) {
          return (TextReference)doc.getCharacterElement(off).getAttributes().getAttribute(TextReference.NAME);
     * Puts a TextReference attribute on the selected text,
     * and switches the referenced text with the new display text.
     * The display text can be an arbitrary String, for instance
     * something pulled from a database.
    private void makeReference() {
        int mark = pane.getSelectionStart();
        int dot = pane.getSelectionEnd();
        if (mark != dot) {
             String ref = pane.getSelectedText();
             String display = "TEST";
             SimpleAttributeSet as = new SimpleAttributeSet();
            as.addAttribute(TextReference.NAME, new TextReference(ref, display));
            // Replace the current selection with the display
            //    text, and give the display text the custom attribute.
            // Later, we can lookup any TextReference strings in the document.
            try {
                doc.replace(mark, dot-mark, display, as);
            catch (Exception e) {
                e.printStackTrace();
     * Custom attribute that just holds the referenced
     * text and the display text so we can always retrieve
     * the reference.
    private static class TextReference {
         public static String NAME = "$reference";
        public String ref;
        public String display;
        public TextReference(String ref, String text) {
            this.ref = ref;
            this.display = text;
     * Custom DocumentFilter that knows to delete an entire
     * String if any character of the String has the TextReference
     * attribute.  This ensures that we don't leave any partial
     * TextReferences lying around.
     * This can be made optional by not using this document.  Use
     * any other StyledDocument if you don't want this functionality.
    private class TextReferenceFilter extends DocumentFilter {
        public void remove(DocumentFilter.FilterBypass fb, int off, int len) throws BadLocationException {
            TextReference ref = getTextReference(off);
            if (ref != null) {
                int dlen = doc.getLength();
                int soff = off;
                while (soff > 0 && ref.equals(getTextReference(soff))) {
                    soff--;
                soff++;
                int eoff = off;
                while (eoff < dlen && ref.equals(getTextReference(eoff))) {
                    eoff++;
                off = soff;
                len = eoff - soff;
            fb.remove(off, len);
     * Tracks the caret and makes it jump over any TextReference strings.
     * Also adjusts the selection to include/exclude the TextReference.
     * This is can be made optional by just not adding this CaretListener
     * to the JTextPane.
    private class TextReferenceCaretHandler implements CaretListener {
        private int lastDot;
        private boolean adjusting;
        public void caretUpdate(final CaretEvent e) {
             if (adjusting) {
                 return;
            adjusting = true;
             int dot = e.getDot();
            int mark = e.getMark();
            final boolean selection = dot != mark;
            if (!selection && dot == lastDot) {
                 return;
            if (dot < lastDot) {
                 TextReference ref = getTextReference(dot);
                 if (ref != null && dot > 0) {
                      do { dot--; }
                      while (dot > 0 && ref == getTextReference(dot));
                      dot++;
            else if (dot > lastDot) {
                int len = doc.getLength();
                TextReference ref = getTextReference(dot-1);
                 if (ref != null && dot < len) {
                      do { dot++; }
                     while (dot < len && ref == getTextReference(dot));
            lastDot = dot;
            if (dot != e.getDot()) {
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {
                        if (selection)
                            pane.moveCaretPosition(lastDot);
                        else
                            pane.setCaretPosition(lastDot);
                        adjusting = false;
            else {
                 adjusting = false;
    public static void main(String[] args) {
        try {
           new TextPaneTest();
        catch (Exception e) {
            e.printStackTrace();
}

Similar Messages

  • Why is alternative text is still visible after an image is displayed (e.g., in Dropbox and Google mail)?

    When I go to my Dropbox page or my Google e-mail page, both the images for icons AND their alternative text is shown (I tried to upload two images illustrating this but the "Upload image" seems to have hung). I am using the lastest version of Firefox for Linux.

    Do you have this pref?
    *browser.display.force_inline_alttext

  • Can anyone help me solve the problem of text displaying very rough on my new ASUS PA279Q display monitor running off my MacBook Pro?

    This is regarding a brand new ASUS PA 279Q, 2560 x 1440 IPS monitor. I'm connected via mini display port (into thunderbolt port on MacBook Pro) to display port on ASUS monitor; using cable ASUS included with the monitor. Mid 2012 MacBook Pro…full specs at bottom of this post.
    I have resolution set at 2560 x 1440 which is the native resolution according to the ASUS spec. I tried the other resolutions available in my System Preferences and text displayed rough with those settings too. I've tried adjusting contrast, brightness and sharpness via the ASUS control panel and didn't solve the problem. Also tried calibrating via Mac's system preferences/display and that did not improve text display either. All the text on this monitor (no matter what software I launch, Finder, InDesign, Illustrator, MS Word, Excel, VMWare Windows XP, Windows versions of Word, Excel, Acrobat, etc, all are consistently rendering text the same way ---  ROUGH and with "HALOS" around each letter.
    All point sizes of text and at various scales, display very rough on the screen. (My comparison is the retina display of my MBP and a Thunderbolt…so those two displays are my expectations.) I'm using the same MBP for both a Thunderbolt display (at work) and this ASUS at my home office.
    On the ASUS it's not as noticeable when the text is on white backgrounds, but I'm a graphic designer and compose images with text all day everyday. Not to mention the specs on this ASUS PA279Q indicate it's built for the professional so I would expect better text rendering. I haven't even addressed color calibration and balance yet, because that won't matter to me if the text won't display any better than it is now.
    I was so hopeful after researching all the specs on this monitor it would be a viable alternative to the glossy display of the Thunderbolt display. (Which, I do love the Thunderbolt display for it's clarity and how it displays crisp, clean text at all sizes. (This ASUS actually displays text decently if I increase the text so each letter is about 4" high. Which is pointless for practical purposes -- that'd be like doing page layout through a microscope!)
    I kept holding off on getting a monitor for the home office thinking the Thunderbolt would be updated soon. I'd be sick if I dropped a grand on piece of 2011 technology only to learn a few days later an updated Thunderbolt display hit the market! Not to mention, I'm praying Apple comes out with a less reflective Thunderbolt display. The glare and reflection is the main reason I looked elsewhere for a large monitor; hence my asking for help. Hoping the ASUS text display issue can be worked out. My expectation is for it to display like the MBP retina and Thunderbolt display text. That possible?
    Alternatively, I guess I could do the Apple Refurb Thunderbolt at $799. And see if there's a decent aftermarket anti-glare I could stick on it?
    Thanks for reading my post. Hope someone can help; offer any suggestions? Words or wisdom?
    Has anyone else had similar issues and figured out a resolution? Help!
    MacBook Pro
    Retina, Mid 2012, 2.3 Ghz Intel i7
    8GB 1600 MHz DDR3
    OS X 10.8.5
    NVIDIA GeForce GT 650M 1024 MB
    ASUS PA279Q

    I uninstalled those two items. It still runs slow on start-up and when opening safari, firefox, iphoto, itunes, etc. It's not snappy like it used to be. Any other ideas? Thanks.

  • Need an extra BOM Alternative Text

    Hi experts,
         In standard SAP we have a provision to write BOM alternative text like the same way I need another BOM Alternative text1 to be included is there any way to do this. and also it should be displayed when you go to item overview 9I.e. new field to be created and it should capture the data from BOM alternative Text1. Is there will be any exit for this.
    Thanks in advance
    Regards
    Venkat

    Hi,
    Thanks for the valuable inputs
    Regards
    Ramana

  • Alternative Text

    I have a graph embedded into a 9i Report (jsp). The report runs fine and displays the graph as expected. I am trying to add alternative text for the entire graph but am not having any success.
    Via the property inspector (for the graph), under the Accessiblity Node, I have enter Alternative Text
    I have also tried entering alternativeText="sometext" on the rw:graph property under the graph node.
    What can I do to ge the ALT tag on my HTML output?

    you are on the right track. the "alternative text" should do the trick.
    if it does not, this might be a bug. check the online help for the graph tag; it might be that there is actually an additional attribute in the graph tag.
    regards,
    ph.

  • Posting Period text display

    Hi Gurus,
    I have a report where i have my GL account hierarchy on my rows and my key figure in column. i have posting period on top of my key figure and my client wants to display the report as
    jan, feb, mar etc till dec. the problem is when i run it through posting period it shows me 1, 2, 3 ...12 instead of text.
    my key figure is populating value based on user exit and i cannot use other time fields like fiscal year/period. i cannot create 12 restricted key figures as my key figure is getting value from exit variable.
    how do i change the text display for 1,2,3 .....12 to jan, feb, mar....dec. is there any sap exit text variable?
    please help
    thanks
    surya

    i cannot create 12 restricted key figures as my key figure is getting value from exit variable.
    why cannot u create restricted key figures ?
    i didnot understand this....
    second question - are u maintaining texts of 0FISCPER3
    if yes then enter RSD1
    enter 0FISCPER3
    edit it
    go to business explorer tab
    over there display as text only and not key
    this way it iwll display just text
    if u rnot maintaitng texts for it
    u have refer above solutions as mentioned by xperts so that u can load texts for 0FISCPER3
    then follow the busines explorer tab changes i suggested...
    if u can create restricted key figure ur problem will solve  easily..

  • Ipod car audio text display

    With hope someone has an answer! I have just brought a new car Mazda 6 along with updating my ipod to the 80gb model. My wish was to take my entire cd collection (quite extensive) to my car and never to use CD's or the delemma of which cd to take. Mazda offered as an accessory an ipod connector. The price tag was considerable however more than worth it in my mind. But how disappointing. I have no text display either on my ipod nor the cars sound system (Bose premimum). This would all be fine if I had stuck to my nano as it's limit of 1000 songs I had to make a decision on. With the 80gb and my entire collection impossible - no idea of the song title, artist etc and no way of chosing what I wish to hear. Not really interested in making playlists as there goes the element of suprise, back to limiting my selection and what the heck I could just as easy (if not more) grab some cds and take to the car. Surely there is a solution to the problem. I presume the reason why I don't get a display on my ipod (other than the Mazda logo) when I connect it is for driving safety reasons but still with hope someone out there can provide me with a solution.
    Anticipated hope
    'Em

    Does it mean that once its fully charged the battery stops operating that the ipod powers up using the d.c. power source?
    No. There is still a slight battery usage when plugged in.
    Do you think it will affect the charging cycle or even the battery life of the ipod by keeping it plugged into the car audio unit using the cd ib-100?
    Yes, but probably not drastically.
    You should drain & charge the iPod fully once a month.

  • How to influence the text display of key figures in the interarctive DP

    Hello all,
    Does anyone know if there is a possibility (BADI, etc.) to change the text display of key figures (not characteristics!) in a planning book/data view?
    I know that you can define a free text in the data view but still, this is only one fixed text and it cannot be changed.
    Reason for the request: We would like to use the same key figure (and hence, indicate 2 different texts) for two different purposes (in different selections) without having to create a new data view.
    Kind regards,
    Klemens

    if you dont want a new data view and might even go to the extent of creating a user exit for this ... here is an idea
    - just create auxillary KF ( or use spare Temp KF depending on what you want to do with the data in the view) for each of these KF with the text
    lets say you have KF1 and KF2 - create KF1A and KF2A
    Make sure KF1A = KF1 and KF2a = KF2
    Now depending on user you can display KF 1 and KF2 or KF1a and KF2a depending on the user by using macros USER() and ROW_VISIBLE(0)

  • How to edit the text displayed in KM Upload link?

    Hi All,
            I want to edit the text displayed in KM Upload link ie "You can upload a file to the repository from your computer. Click "Show Properties" to assign another name or to change the settings".
    I tried searching for the resource bundle from which the above text is displayed but couldnt find it.
    Can anyone help?
    Thanks in advance.
    Regards,
    Pooja.

    Hi Pooja
    You can find the text in <b>ResourceEditControl**.properties</b> file, which is available under   <i>com.sap.km.cm.ui\lib\km.appl.ui.edit_api\com\sapportals\wcm\control\edit</i>..
    The text is represented by the key <b>txtUploadControl</b>..
    Regards,
    Sandip

  • AOL stripping pdf from "multipart/alternative" text email

    Hi! I am using MYOB AccountEdge and it has a function within the program to send out statements as pdf attachments to a text email. As of the beginning of this year, AOL is stripping off the pdf attachment, but the text email goes through. Last year, no problem - the attachments were received.
    I can send the attachment to the AOL accounts successfully if I attach it to a new text mail message from the mac Mail program.
    In examining the Long Headers, it appears the only difference, I can see is that the email where the pdf attachment is stripped is "multipart/alternative" and the email where is goes through is "multipart/mixed".
    As the MYOB program seems to send through Mail, at least the sent message shows up in the Sent folder, is there a way to force "multipart/mixed" through a command in Terminal? Or do I need to continue to do battle with MYOB?
    Anyone else having pdf's stripped when sending a "multipart/alternative" text email to AOL?
    Thanks for any help/ideas.
    Peter Truce

    Thanks for the help, Ernie. I did note that sometimes, not today, the message would take a very long time to get to my test AOL account - perhaps 12 hours, but it would eventually show up.
    Of course not all of my customers use AOL and everyone else is receiving the statement emails correctly. Just AOL clients and usually they are using a PC, curiously. I have one client with a Mac who is getting them OK on her AOL account.
    The brush image has been there for say, 5 years? Hopefully that is not the problem as I really, really like the brush.
    I do agree with what you are suggesting: This is a MYOB problem and MYOB will have to solve it. But thanks for identifying the thing. I will be hopping on the Tech Support Desk tomorrow - can't get through by phone on Mondays usually.
    Peter Truce

  • (FM8p277) Crashes when saving first doc in book after changing conditional text display

    That was a mouthful :-)
    Okay, this happens with any of the books that I work on --- it never happened with Frame 7.
    I have a book containing several documents.
    The documents contain several conditional text segments.
    Start new Framemaker session, open book, open all documents.
    Change conditional text display (from Show All to Show Selected, or vice-versa).
    From the book, choose Save All (or from the *first* document, choose Save). The following text appears in a 'FrameMaker dialog': "File <filename of first document>.fm has changed on the disk since you last opened or saved it. Someone else has probably modified the file. Do you want to save it anyway?
    Click OK. All of the files save properly. (If I had clicked Cancel, the first file would be skipped and all other files would save.)
    Change conditional text display again (note: this could even be for a different book at this point, I believe, but will have to verify).
    (Repeat step 3): The same text appears again in the dialog.
    Click OK. FrameMaker crashes while trying to save the first file. (If I had clicked Cancel, the first file would be skipped and all other files would save. However, if I attempt to save the first file afterward, FrameMaker still crashes.)
    Anybody have any insight into this? Am I the only one this happens to? Argh :-)
    Thanks.

    Sorry, the only answers I got were on the forum and nothing worked
    That being said, at least now I know I'm not crazy! (Sorry it had to
    happen to you, though.)
    As it stands, I've been training myself to make sure that after the
    first time I toggle the settings, I do the save, and then make sure to
    save all, quit, and restart FrameMaker before I attempt another toggle.
    On the odd occasion that I don't do that and get the warning message, I
    select Cancel (which lets the rest of the files save), quit, restart,
    and then make sure I update the first document appropriately.
    All the while cursing and swearing, of course
    As an aside... if you find a solution, please let me know about it if
    you remember.
    Thanks.
    John

  • When I open FF there is no text displaying(menus, content, etc.), and most of the window is blacked out. For example... I can is the the firefox button on the t

    When I open FF there is no text displaying(menus, content, etc.), and most of the window is blacked out. For example... I can see the the firefox button on the top left corner, when I go to it the drop down list drops and there is no text, if I move down the drop down I hit where there is a slide out in that drop down and no text is there. So, to start in safe mode you need to go to the firefox button, and click on start in safe mode. I can't See safe mode or click on anything were safe mode should be.

    hello, close all firefox windows & hold the shift-key while opening firefox in order to launch it in safemode. in the first dialog just choose "continue in safemode" and go to firefox > options > advanced > general. in there disable hardware acceleration, restart firefox normally again and see if this has changed anything.
    also see [[Upgrade your graphics drivers to use hardware acceleration and WebGL]]

  • How to center the text displayed in a JList

    Hi,
    The width of the JList display area is wider than the text displayed. I tried to center the text displayed to make it look nicer. I had tried using "setAlignmentX(Component.CENTER_ALIGNMENT)" in my own ListCellRenderer class but did not work. Any idea how to center the text?
    Fai.

    Yes, I am using JLabels in my renderer and the following is the code:
    public class MyCellRenderer extends JLabel implements ListCellRenderer {
         private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);
         public MyCellRenderer() {
              setOpaque(true);
              setIconTextGap(12);
         public Component getListCellRendererComponent(
              JList list,
              Object value,
              int index,
              boolean isSelected,
              boolean cellHasFocus)
              String entry = (String)value;
              setText(entry);
              setFont(new Font("Ariel", Font.BOLD, 18));
              setAlignmentX(Component.CENTER_ALIGNMENT);
              if(isSelected) {
                   setBackground(HIGHLIGHT_COLOR);
                   setForeground(Color.white);
              } else {
                   setBackground(Color.white);
                   setForeground(Color.black);
              return this;
    Can you point out where to implement the centering logic?
    Thanks,
    Fai.

  • Unable to Add alternative text and tooltips to your images

    Hello,
    I am using Muse CC in Apple iMAC machine.  The build version of Muse CC is 232. 
    Having watched the video, http://tv.adobe.com/watch/learn-adobe-muse-cc/using-titles-and-alt-text-to-images/, I am unable to bring up the image property window when I press the right hand click button of my Apple Mouse. 
    As such, I am unable to add alternative text and IMG Text to my images including the logo, facebook and Twitter Logos. 
    Can someone please tell me how to resolve my issue?  How come I unable to bring up the image property when I press the right hand click on the mouse.  The image property is also not shown in the menu of Muse CC.
    Thank you.
    Maxplus.

    Hello Maxplus,
    Try doing CTRL+Click once to see if it works. Also, if an image is added as a fill, it doesn't bring up the Add alternative text and tooltips option, because then it is added as a background and not placed as an image.
    Cheers
    Parikshit

  • Text displays differently in pdf

    When I export one particular InDesign file (Mac CS 5.5, Version 7.5) to PDF the body text font displays heavier on the 2nd and third page, though it is it's normal weight on the first page. I have rebuilt the document exporting to pdf after the text was formatted, after the images were placed and the body text displays the same on all pages. After I add hyperlinks to urls in the sidebar text, export to pdf then the body text displays heavier on pages two and three than on page one.
    I am not sure if this is an InDesign issue or an Acrobat issue. How do I fix it?

    It's a known transparency issue. Keep the text above the transparent objects might help, but probably won't.

Maybe you are looking for

  • Insert a flash file to iweb 09 or an easy way to display photos

    Goal: have a photo space on my home page that plays automatically - dissolving one to the next. I am trying to either insert a flash file to my home page http://web.me.com/ksporterproductions/PWF/Home.html I've used the html widget with this code: Fl

  • Any news or comment on Java to H.264

    Is this forum of the used Forum on JMF? I would like to hear more news and comments on Java to H.264? Any codec developed by anyone to this new standard? Is Java fast enough to run H.264 codec on moderate computer, like PC with P3 800Mhz? Anyway, the

  • When I try to download CC or PS I get an error message. I paid for CC two days ago; rebooted,etc.

    When I try to download CC or PS I get an error message. I paid for CC two days ago and am still getting this. I rebooted several times with same result. This is the message: We're sorry. Something seems to be wrong on our end. Please try again later.

  • Groupwise 2014: How do I change the FID of a user

    Hello! In ConsoleOne you can easily change a users FID, but is it possible to do that in the new Administration Console in Groupwise 2014? regards Daniel

  • Several unrelated issues

    I have several unrelated issues. 1) My computer recently started failing to startup. It flashes an image of a globe, and then an image of a finder folder alternated with a questionmark, and then, if I'm lucky, proceeds to normal start up. What is goi