Text pane problem

Hi guys,
I need a component which acts as a chat screen allowing me to append messages. Each chat message may be a different colour. I also need to set the font of the pane via my look and feel. This font is not included in html.
First I tried using a JEditorPane which worked fine, I could change the colour of the text using html formatting but could not use my own font.
My next option was to use a JTextPane (see code below) but when I append lots of messages the screen flickers and the scroll pane jumps to the top.
public class JLTextPane extends JTextPane {
    public void append(Color c, String s) {
        setEditable(true);
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
        StyleConstants.Foreground, c);
        setCaretPosition(getDocument().getLength()); // place caret at the end (with no selection)
        setCharacterAttributes(aset, false);
        replaceSelection(s); // there is no selection, so inserts at caret
        setCaretPosition(getDocument().getLength());
        setEditable(false);
    public void appendLine(Color c, String line) {
        if(getDocument().getLength() == 0) {
            append(c, line);
        } else {
            append(c, "\n" + line);
}I have run out of ideas. Any help?
Thanks

I could not find your alternative approach from your last post. I understand it must be frustrating dealing with people who are new to swing when you are so experienced yourself but after all this is a forum and thats why I'm here.
I have written you a test program which should be runnable.
public class MessagePanel extends JPanel {
    //the size of the panel
    private static final Dimension SIZE = new Dimension(400, 175);
    //the input box
    private JTextField _input;
    //the text pane itself
    private JTextPane _pane;
    public MessagePanel() {       
        initPanel();
        createPanel();
    public void initPanel() {
        setLayout(new GridBagLayout());
        setPreferredSize(SIZE);
    public void createPanel() {
        //create and setup the text pane
        _pane = new JTextPane();
        _pane.setEnabled(false);
        //create and setup the scrollable pane
        JScrollPane scrollable_pane = new JScrollPane(_pane);
        scrollable_pane.setPreferredSize(new Dimension(SIZE.width - 5, SIZE.height - 26));
        scrollable_pane.setVerticalScrollBarPolicy(
                    ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        //add the components to the main panel
        GridBagConstraints c = new GridBagConstraints();
        c.gridx = 0;
        c.gridy = 0;
        add(scrollable_pane, c);
    private void append(Color colour, String message) {
        if(colour == null) {
            colour = Color.BLACK;
        StyleContext sc = StyleContext.getDefaultStyleContext();
        AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY,
                StyleConstants.Foreground, colour);
        _pane.setCaretPosition(_pane.getDocument().getLength()); // place caret at the end (with no selection)
        _pane.setCharacterAttributes(aset, false);
        _pane.replaceSelection(message); // there is no selection, so inserts at caret
        _pane.setCaretPosition(_pane.getDocument().getLength());
    private void appendLine(Color c, String line) {
        if(_pane.getDocument().getLength() == 0) {
            append(c, line);
        } else {
            append(c, "\n" + line);
    public static void main(String[] args) {
        MessagePanel panel = new MessagePanel();
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
        Color[] colours = new Color[3];
        colours[0] = Color.RED;
        colours[1] = Color.BLUE;
        colours[2] = Color.ORANGE;
        for(int i = 0; i < 100; i++) {
            panel.appendLine(colours[i % 3], "Line: " + i);
}Could you possibly alter my code so that it can append lines without flicker and prevents the user from editing the JTextPane.
Thanks again.

Similar Messages

  • Cant get automatic scrolling text pane to work from other classes

    Hi guys, I've been creating a program that utilises JInternalFrames, one of which frames is an "event log" which is simply a Document I append text to, problem is I'm getting some strange logic errors. It works fine if it's just left alone and adds text from its internal timer method, but as soon (sometimes on 3rd or 4th call) of it's static method called 'append' it starts spewing out error message - mainly ""AWT-EventQueue-0" java.lang.NullPointerException", and stops working.
    Here is my internal frame (a MyJDesktopPane component), with its internal appendText that works fine.
    import java.awt.event.*;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.*;
    public class EventLog extends JInternalFrame {
        public EventLog() {
            super("",
                      false,      //resizable
                      false,      //closable
                      false,      //maximizable
                      true);     //iconifiable
            atp = new ELInternal();
            this.getContentPane().add(new JScrollPane(atp));
            this.setSize(200, 200);
            this.setVisible(true);
            // Add some text every second
            Timer t = new Timer(1000, new ActionListener() {
              public void actionPerformed(ActionEvent evt) {
                String timeString = fmt.format(new Date());
                atp.appendText(timeString + "\n");
              SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
            t.start();
        public static void append(String in)
             try {
                       atp.appendText(in + "\n");
             } catch ( Exception e  ){}
        static ELInternal atp;
    }Here is the internal panes content:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class ELInternal extends JTextPane {
      public ELInternal() {
        super();
      public ELInternal(StyledDocument doc) {
        super(doc);
      // Appends text to the document and ensure that it is visible
      public  void appendText(String text) {
        try {
          Document doc = getDocument();
          // Move the insertion point to the end
          setCaretPosition(doc.getLength());
          // Insert the text
          replaceSelection(text);
          // Convert the new end location
          // to view co-ordinates
          Rectangle r = modelToView(doc.getLength());
          // Finally, scroll so that the new text is visible
          if (r != null) {
            scrollRectToVisible(r);
        } catch (BadLocationException e) {
          System.out.println("Failed to append text: " + e);
    }So every time I call "append" which another classes need to be able to call to update it's current event, It just doesn't work... ? I've been staring at this code for hours, think it's going all matrix on me.

    Isn't this the "*new* to java" forum? I know what error messages are for, if I understood it I wouldn't be here asking the question!!!!
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
         at javax.swing.text.BoxView.updateChildSizes(Unknown Source)
         at javax.swing.text.BoxView.setSpanOnAxis(Unknown Source)
         at javax.swing.text.BoxView.layout(Unknown Source)
         at javax.swing.text.BoxView.setSize(Unknown Source)
         at javax.swing.text.BoxView.updateChildSizes(Unknown Source)
         at javax.swing.text.BoxView.setSpanOnAxis(Unknown Source)
         at javax.swing.text.BoxView.layout(Unknown Source)
         at javax.swing.text.FlowView.layout(Unknown Source)
         at javax.swing.text.BoxView.setSize(Unknown Source)
         at javax.swing.text.BoxView.updateChildSizes(Unknown Source)
         at javax.swing.text.BoxView.setSpanOnAxis(Unknown Source)
         at javax.swing.text.BoxView.layout(Unknown Source)
         at javax.swing.text.BoxView.setSize(Unknown Source)
         at javax.swing.plaf.basic.BasicTextUI$RootView.setSize(Unknown Source)
         at javax.swing.plaf.basic.BasicTextUI.getPreferredSize(Unknown Source)
         at javax.swing.JComponent.getPreferredSize(Unknown Source)
         at javax.swing.JEditorPane.getPreferredSize(Unknown Source)
         at javax.swing.ScrollPaneLayout.layoutContainer(Unknown Source)
         at java.awt.Container.layout(Unknown Source)
         at java.awt.Container.doLayout(Unknown Source)
         at java.awt.Container.validateTree(Unknown Source)
         at java.awt.Container.validate(Unknown Source)
         at javax.swing.RepaintManager.validateInvalidComponents(Unknown Source)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Sourc
    e)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)

  • Can't write in the text pane of Hotmail. Working on other browsers.

    Can't write in the text pane of Hotmail.

    * "Clear the Cache": Tools > Options > Advanced > Network > Offline Storage (Cache): "Clear Now"
    * "Remove the Cookies" from sites that cause problems: Tools > Options > Privacy > Cookies: "Show Cookies"
    Start Firefox in [[Safe Mode]] to check if one of your add-ons is causing your problem (switch to the DEFAULT theme: Tools > Add-ons > Themes).
    See [[Troubleshooting extensions and themes]] and [[Troubleshooting plugins]]

  • Text box problem or question

    I'm having the text field problem. I have two text boxes (inside my .fla file) one i can add more text without the box expanding and can  then select the text and croll down to view the missing text and the other one just gets longer the more text I add. I'm trying to duplicate the text box that does not expand the more text I add to it.
    All the settings in the properties are the same on both and I've tried it in MX and CS3 and the both have the same properties in both.
    I'm stumped can anyone help.
    I'm attaching the file.
    Thanks!

    If you right click the textfield on the stage you can select the "scrollable" option for it.  Another option to duplicate the textfield is to copy/paste it.

  • Question on the known solution to the "Three pixel text jog" problem

    Hello,
    I'm "browser-checking" my website using Dreamweaver CS4 tool for that. I've got in various places the "three pixel text jog" IE problem. I followed the link to solution proposed by DW. It says I should add an IE conditional statement in the <head> part, so that I can define the CSS zoom property for that particular element. Hence, something like that:
    <!--[if IE]>
    <style type="text/css">
    #Content p { zoom: 1; } /* three pixel text jog IE bug */
    </style>
    <![endif]--> 
    (assuming the problem occurs for a <p> inside my #Content div.)
    My question is: can I replace this by
    <!--[if IE]>
    <style type="text/css">
    #Content * { zoom: 1; } /* three pixel text jog IE bug */
    </style>
    <![endif]--> 
    For another browser problem (prevent the browsers from using some of their own default settings), it was advised to reset the margin, padding and border properties using:
       border: 0;
       margin: 0;
       padding: 0;
    (although in my case I had to later remove border: 0; because it would prevent default buttons of forms to be displayed as buttons.)
    Does this * really mean "anything"? Is it valid as used above for fixing the three pixel text jog problem? If not, do I really have to define this zoom property for any single HTML element for which it occurs? (It currently occurs for some headers, <div>, "<div> <div>" sequence, some <p>.)
    Any comment welcome...
    Emilie
    P.S.: I tried it and DW doesn't flag that problem any more, but I'm unsure how much I can trust it.

    The behavior is unexpected. The file paths are
    correct?

  • We bought an iphone 4s for our daughter. We transfered it to straight talk. She can make calls and text no problem. She can use the WiFi but is unable to use the internet or mms. How do we update the APN?

    We bought an iphone 4s for our daughter. We transfered it to straight talk. She can make calls and text no problem. She can use the WiFi but is unable to use the internet or mms. How do we update the APN?

    To clarify for anyone who is still having any problems doing this.
    1. Unlock your phone with the carrier ( I know the process will work if it is jail broken but I am assuming you dont want to void the warranty on your phone) NOTE: even if you purchased the phone outright at Wal-Mart it is still locked to ATT so you will have to unlock the phone.  If it's already unlocked skip to step 2.  This works and will work even if you update the phone. 
    1a Here is the link to unlock a ATT iphone. Simply follow the instructions https://www.att.com/deviceunlock/client/en_US/
    2. Get a T- mobile SIM. Even if you don't want the service, if you feign interest, they will send you one for free or 99cents. If you need it now you can get one at a T-mobile store too.
    3. Once you have both your Straight talk SIM and your T-mobile SIM follow these instructions:http://www.youtube.com/watch?v=mFFf5uqk18M
    4. If you have any remaining questions look at all the responses posted previously on this thread or check out the Howard Forums Wiki: http://wiki.howardforums.com/index.php/Straight_Talk_iPhone
    Everything should work flawlessly at this point.  If not let me know and I'm happy to help when I can.  I hope this makes doing this very easy for everyone in the future. God Bless -J

  • Possible to change a text pane in card template to photo pane?

    I am working on a holiday card, but would like to use an additional photo where there is currently a text box/pane.  Is there any way to change this text pane to another photo?  Simple drag and drop does not seem to work.
    Thanks,
    Boris

    LOL. man what a day! Ever feel like when you do anything it
    takes an act of congress? As if walking through quicksand? Sheesh.
    Yes, here is the link you need:
    Click
    here to visit the Capitvate Feature Request/Bug Reporting form
    Cheers... Rick

  • Font / text edit problem in photoshop CS6

    Hi there,
    I have a strange text edit problem in Photoshop CS6 running on Mavericks.
    Every time I use the text-tool in PS, write a sentence, mark it and change something like color, font size etc., the marked text vanishes.
    I have to "undo" the last step and the changed text appears again.
    Every time!
    I have a clean installed CS6 with no plugins and no other than system fonts installed.
    Everything on a new Mac Pro with OS X 10.9.5
    Any clues? Thanks.

    Do you have the latest updates for photoshop cs6?
    You can use Help>Updates from within photoshop cs6 to check if there are any available.
    Also, if you go to Help>System Info from within photoshop cs6, you can see the Photoshop Version in the top line.
    You should be on version 13.0.6
    See if turning off Dictation solves the issue.
    Go to System Preferences ---> Dictation and Speech -----> select OFF radio button .

  • Selecting html source from the text pane

    Help!!
    I am selecting text in the HTMLEditor text pane but when I look at the selected text it does not include tags like image and table tags. I would like to somehow grab the selected html source based on what is selected in the text pane. Is there a way to map the selected text in the editor textpane to the html in the editor sourcepane? I have not been able to find an answer in previous threads.
    thanks,
    Steve

    here is the easiest way i know
    using JEditorPane from the swing package
    JEditorPane sourceViewer = new JEditorPane(http://www.google.com);
    System.out.println(sourceViewer.getText());
    or
    JTextArea.setText(sourceViewer.getText);
    several things to concider....
    1. you dont have to add the component to abuse it, ie you dont have to show the JEditorPane you can just use its functionality
    2. you cant JUST display the text in anything made to display html unless you removed the <html> tag. but that wont stop you from printing it or putting it into a JTextArea

  • Retriving attributes for the  content of a text pane

    How to know what character atrributes has been imposed ont he content from the JTextPane.
    Iam having twp text panes say one for typing and other for displaying
    here in the type area i types some content with different character atrributes
    some words with bold some words with italic etc,
    So my question is how to retieve the content and its attributes.
    Message was edited by:
    Ramxy

    Hi,
    I think you have doen some thing like this in PBO.
    screen_field_name = 'some value'.
    So now in PAI you can do the following.
    CASE sy-ucomm.
         WHEN 'F_CLEAR'.    " Fcode for the clear button in the screen.
          CLEAR : field_name.
      ENDCASE.
    If the field is a mandatory field then you need to create a AT EXIT module and write the same code in that.
    Hope it helps you.
    Thanks,
    Sri.

  • N96 text sending problem pls help!

    Hi, i have a nokia N96, on friday it just stopped sending my texts,
    the problem started as i was texting my friend as normal, then she replied saying she had got the same msg 8 times! since then all my texts have got stuck in my outbox!
    whats going on?
    I have backed up my contacts incase i need to restore the phone but i want to avoid doing that if possible as i dont want to loose my photos and music (unless someone can tell me how to back those up too!)
    Can anyone offer any advise, other than chuck it accross the room?!
    Oh and also, i have 2 multimedia msg in my inbox that wont delete! could this be causing the problem? When i try to delete it says "already in use"  where? i cant find them!
    thanks
    xXx
    Kudos! Thanks!
    Edit Post Subscribe to This Topic's RSS Feed Highlight This Post Print This Post E-Mail this Post to a Friend Report Abuse to a Moderator
          Options       

    I have had a similar problem on my 5700, started out the same, people saying my text was coming trhough 3 or 4 times, then it stopped sending.  I checked the message centre phone number with my provider, which was correct, and then it would not let me into the the message centre to even edit the number?? I have tried a factory reset and a firmware update.  Does anyone else have any ideas??

  • Limiting Scrollable Text Pane Memory Consumption

    Hi!
    I have written an interface for an online application which will require to operate continuously. Every couple of seconds a new line of text is added to a Scrollable Text Pane.
    This works well, however, I would like to ensure that I limit the amount of memory used so the application does not run out of memory.
    Can anyone suggest a way for me to do this?
    Thanks in advance,
    John

    Hi again,
    hm ... with a StringTokenizer like this
    StringTokenizer st = new StringTokenizer(getText(),"\n");
    if (st.hasMoreTokens())
    int cutLength = st.nextToken().length()+1;
    // here remove that part of text as posted before
    hope this helps now - it only removes, if there is a complete line
    greetings Marsian

  • Text overlapping problem

    Since I upgraded to 10.4.10, I dont know if I did something wrong but I have bad text overlapping problems in Safari and some other apps such as Software Update, I first noticed the overlapping when editing a Wikipedia article and in the text box the text kept overlapping. Another site where it is very noticeable is in Facebook, here's a screenshot:
    Even on this site it's pretty bad. It's the worst in text-boxes like in the one I'm typing in right now.
    This is driving me crazy, anyone else have this problem or know how to fix it? Thanks.
    Message was edited by: Johnny K.

    Ok, Johnny --
    I hated to ask cause it's "Old School."
    If you shut down your Mac every night,
    you should have something on your Mac that will run cron scripts,
    and do other helpful things for you.
    I personally use YASU.
    I run it about 1x month.
    It's free or donation-ware
    it's written just for Macs
    and is excellent.
    Here's where to go for more info on it:
    http://jimmitchell.org/projects/yasu/
    The new Macs were built to stay on 24/7.
    When you shut them off at night, you stop the regular
    maintenance it already has scheduled. YASU (or similar apps)
    will take care of everything for you.

  • On the Text pane of Keyboard preferences, shortened texts disappeared, not remembering anything

    Hey there, I'm not really sure when this happened, but sometimes after the update to 10.9.3, all the text shorteners I had set-up in the Text Pane of the Keyboard Preferences, have disappeared!
    Even worse, when I try to set up other shorteners, nothing sticks. As soon as I leave the pane, and I come back to it, whatever texts I just added, disappear again.
    Did this happen to anyone else, or is it just me?
    Thanks!

    Some idiot programmer or project manager decided that Mavericks users don't need those any longer. The only way to put them back is to muck around with each user's hidden .GlobalPreferences.plist file stored in /Users/username/Library/Preferences/. You have to add this to that plist file. It might be that your plist is corrupt. In that case, move it to the Desktop, log out and back in. That should put down a default version, but that's just a WAG.
    NSUserReplacementItems =     (
                on = 1;
                replace = "(c)";
                with = "\\U00a9";
                on = 1;
                replace = "(r)";
                with = "\\U00ae";
                on = 1;
                replace = "(p)";
                with = "\\U2117";
                on = 1;
                replace = TM;
                with = "\\U2122";
                on = 1;
                replace = "c/o";
                with = "\\U2105";
                on = 1;
                replace = "...";
                with = "\\U2026";
                on = 1;
                replace = "1/2";
                with = "\\U00bd";
                on = 1;
                replace = "1/3";
                with = "\\U2153";
                on = 1;
                replace = "2/3";
                with = "\\U2154";
                on = 1;
                replace = "1/4";
                with = "\\U00bc";
                on = 1;
                replace = "3/4";
                with = "\\U00be";
                on = 1;
                replace = "1/8";
                with = "\\U215b";
                on = 1;
                replace = "3/8";
                with = "\\U215c";
                on = 1;
                replace = "5/8";
                with = "\\U215d";
                on = 1;
                replace = "7/8";
                with = "\\U215e";
                on = 1;
                replace = teh;
                with = the;

  • Next focusable componentwhen using a text pane

    I am using nextFocusableComponent and it works grand with textFields but how do I use it with a textPane. By pressing tab it will just go onto a new line. I want it to tab to the next item. I want to use "return/enter" to get the next line on the text pane.

    Swing related questions should be posted in the Swing forum.
    Here is my answer for a JTextArea. I assumes its the same for a JTextPane:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=609727

Maybe you are looking for