JTextPane(continued)

Hi, I have read the post about the JTextPane wrapping and it works fine. However, when I load a file that has a lot of characters (29,000+)
and I want to display them on one line, it wraps the characters in a paragraph of lines and creates big blank spaces at its sides(I can still scroll, there's just nothing written). I am wondering if there is a setting that would force a single line to be continued endlessly with a horizontal ScrollBar.
Thanks.

I'm running JDK1.3 on windows 98. The requestFocus() method does not work unless it is executed after the JFrame is shown. Maybe this is your problem. The following sample program will help illustrate this.
1) run the program as is. Focus should be on the text area as you select a tab.
2) Comment out the 'newTab' methods in the main method. Uncomment the 'newTab' methods in the constructor. This time focus will remain on the tab as you select it.
Hope this helps.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class TestTabbedPane extends JFrame
     JTabbedPane tabbedPane;
     public TestTabbedPane()
          tabbedPane = new JTabbedPane();
          tabbedPane.setPreferredSize( new Dimension(300, 200) );
          getContentPane().add(tabbedPane);
//          newTab( "one" );
//          newTab( "two" );
//          newTab( "three" );
     private void newTab(String text)
          JTextArea textArea = new JTextArea( text );
          JScrollPane scrollPane = new JScrollPane( textArea );
          tabbedPane.addTab( text, scrollPane );
          tabbedPane.setSelectedIndex( tabbedPane.getTabCount() - 1 );
          textArea.requestFocus();
     public static void main(String args[])
TestTabbedPane frame = new TestTabbedPane();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
          frame.newTab( "one" );
          frame.newTab( "two" );
          frame.newTab( "three" );

Similar Messages

  • Help! How to use JTexpPane smooth?

    Hi!
    While append text to a JTextPane continuously and quick,
    it uses much memery and CPU,
    and how to make it smooth?
    the code rough like following:
    JTextPane pane = new JTextPane();
    Thread thead = new Thread(){
        public void run()
       while(true)
       try{
          Thread.sleep(10);
           if(pane.getDocument().getLength()>2000000)
      pane.getDocument().remove(100000,pane.getDocument().getLength());
    pane.getDocument().insertString(pane.getDocument().getLength(),"I Love this game\n",null);
    catch(Exception ex)
    }Thank you very much!

    Not really sure what your are trying to do, but of course your CPU usage is high. It looks like you are creating an infinite loop with your Thead.
    Maybe this posting is what you are trying to do:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=689486

  • ComponentView does not redraw component in JTextPane Cell Rend

    We have created a JTable implementation that uses JTextPanes as cell renderers/editors so that text styles and the like are available. We want insert a component, such as a JButton, into the JTextPane. However, the component is only visible when the cell is in an editable state. In the renderer, the ComponentView looks like it has set aside the space where the component is to be, but the component is not visible.
    I have looked at this problem for several days now, and have only determined that this seems to be occuring at a low level. What I have found is that the ButtonUI's update method is not called when the document is in the cell renderer, while it seems called continuously in the cell editor (on each caret blink).
    Does anybody have any insight as to the problem? I have submitted this as a bug to Sun but wanted to find out if anybody else has come across anything similar to this.
    Thank for any help.
    Steve Feveile
    Here is sample code to reproduce the problem:
    // Main Class
    * Main frame for the testing of the component not painting. This simplifies
    * an issue we have come across when trying to set up using a JTextPane as a
    * renderer/editor as the cells in a table.
    * Under these conditions we have found that a component inserted into the JTextPanes document
    * only appears in the editing state of the cell, whereas the rendering state leaves
    * the spacing for the component but does not make it visible.
    * Note that creating a JTextPane with the one of these documents will show the component,
    * even when not editing.
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class tableFrame extends JFrame
         public tableFrame()
              //set up frame
              getContentPane().setLayout(new BorderLayout());
              setSize(500,300);
              setTitle("Table Missing Component Test");
    addWindowListener(
         new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                             setVisible(false);                         
                   System.exit(0);     
              //set up components the table
              JTable table = new JTable(createDocumentTableModel(2,2));
              table.setRowHeight(60);
              //set the default renderer/editor to use the JTextPane implementation
              for (int x = 0; x < table.getColumnCount(); x++) {
                   table.setDefaultEditor(table.getColumnClass(x), new TextPaneCellEditor());
                   table.setDefaultRenderer(table.getColumnClass(x), new TextPaneRenderer());
              JScrollPane pane = new JScrollPane(table);
              getContentPane().add(pane, BorderLayout.CENTER);
              //this adds a textpane without the table involved
              //uising the same way of inserting a document
              JTextPane tPane = new JTextPane();
              DefaultStyledDocument doc = new DefaultStyledDocument();
              try
                   doc.insertString(0, "Some text in a JTextPane", null);
                   JButton b = new JButton("Button");
         SimpleAttributeSet inputAttributes = new SimpleAttributeSet();
              StyleConstants.setComponent(inputAttributes, b);
              doc.insertString(0 , " ", inputAttributes);
              catch (Throwable t)
                   System.out.println("createDocumentTableModel error: " + t.getMessage());
              tPane.setDocument(doc);
              tPane.setSize(490, 60);
              JScrollPane pane2 = new JScrollPane(tPane);
              getContentPane().add(pane2, BorderLayout.SOUTH);
         * this creates a table model where the documents are the value
         * in each cell, and the cell renderer/editor can use this instead
         * of a string value
         private TableModel createDocumentTableModel(int row, int col)
              Vector headerData = new Vector();
              Vector tableData = new Vector();
              for (int i=0;i<row;i++)
                   headerData.add("Column" + i);
                   Vector rowData = new Vector();
                   for (int j=0;j<col;j++)
                        DefaultStyledDocument doc = new DefaultStyledDocument();
                        try
                             //this inserts some string to see that this is visible
                             //when editing and rendering
                             doc.insertString(0, ("Row: " + i + ", Column: " + j), null);
                             //this button will only be visible when the cell is in
                             //an editing state
                             JButton b = new JButton("Button" + i + "-" + j);
                   SimpleAttributeSet inputAttributes = new SimpleAttributeSet();
                        StyleConstants.setComponent(inputAttributes, b);
                        doc.insertString(0 , " ", inputAttributes);
                        catch (Throwable t)
                             System.out.println("createDocumentTableModel error: " + t.getMessage());
                        rowData.add(doc);
                   tableData.add(rowData);
              return new DefaultTableModel(tableData, headerData);
         //starts the ball rolling
         static public void main(String args[])
              (new tableFrame()).setVisible(true);
    // Custom Cell Editor
    * Sets the editor to use a JTextPane implementation
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.table.*;
    import javax.swing.event.*;
    import java.util.EventObject;
    import java.io.Serializable;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TextPaneCellEditor implements TableCellEditor
    /** Event listeners */
    protected EventListenerList listenerList = new EventListenerList();
    transient protected ChangeEvent changeEvent = null;
    protected JTextPane editorComponent;
    protected EditorDelegate delegate;
    protected int clickCountToStart = 1;
         * constructor.
    public TextPaneCellEditor() {
              editorComponent = new JTextPane();
              //use 1 click count to edit a cell
              clickCountToStart = 1;
              * controls the values of the editor
              delegate = new EditorDelegate() {
                   * sets the text value cell.
                   * @param value - value to set in the document
                   public void setValue(Object value) {
                        if (value instanceof Document)
                             editorComponent.setDocument((Document) value);
                        else
                             editorComponent.setText("");
                   * gets the text value cell.
                   * @return the document in the textpane
                   public Object getCellEditorValue() {
                        return editorComponent.getDocument();
         // implements the setting the value for the editor
         public Component getTableCellEditorComponent(JTable table, Object value,
                   boolean isSelected, int row, int column) {
              if (value != null)          
                   delegate.setValue(value);
              else
                   delegate.setValue("");
              return editorComponent;
    // Implementing the CellEditor Interface
         // implements javax.swing.CellEditor
         public Object getCellEditorValue() {
              return delegate.getCellEditorValue();
         // implements javax.swing.CellEditor
         public boolean isCellEditable(EventObject anEvent) {
              if (anEvent instanceof MouseEvent) {
                   return ((MouseEvent)anEvent).getClickCount() >= clickCountToStart;
              return true;
    // implements javax.swing.CellEditor
         public boolean shouldSelectCell(EventObject anEvent) {
              return delegate.shouldSelectCell(anEvent);
         // implements javax.swing.CellEditor
         public boolean stopCellEditing() {
              fireEditingStopped();
              return true;
         // implements javax.swing.CellEditor
         public void cancelCellEditing() {
              fireEditingCanceled();
    // Handle the event listener bookkeeping
         // implements javax.swing.CellEditor
         public void addCellEditorListener(CellEditorListener l) {
              listenerList.add(CellEditorListener.class, l);
         // implements javax.swing.CellEditor
         public void removeCellEditorListener(CellEditorListener l) {
              listenerList.remove(CellEditorListener.class, l);
         * Notify all listeners that have registered interest for
         * notification on this event type. The event instance
         * is lazily created using the parameters passed into
         * the fire method.
         * @see EventListenerList
         protected void fireEditingStopped() {
              // Guaranteed to return a non-null array
              Object[] listeners = listenerList.getListenerList();
              // Process the listeners last to first, notifying
              // those that are interested in this event
              for (int i = listeners.length-2; i>=0; i-=2) {
                   if (listeners==CellEditorListener.class) {
                        // Lazily create the event:
                        if (changeEvent == null)
                             changeEvent = new ChangeEvent(this);
                        ((CellEditorListener)listeners[i+1]).editingStopped(changeEvent);
         * Notify all listeners that have registered interest for
         * notification on this event type. The event instance
         * is lazily created using the parameters passed into
         * the fire method.
         * @see EventListenerList
         protected void fireEditingCanceled() {
              // Guaranteed to return a non-null array
              Object[] listeners = listenerList.getListenerList();
              // Process the listeners last to first, notifying
              // those that are interested in this event
              for (int i = listeners.length-2; i>=0; i-=2) {
                   if (listeners[i]==CellEditorListener.class) {
                        // Lazily create the event:
                        if (changeEvent == null)
                             changeEvent = new ChangeEvent(this);
                        ((CellEditorListener)listeners[i+1]).editingCanceled(changeEvent);
    // Protected EditorDelegate class
    protected class EditorDelegate implements ActionListener, ItemListener, Serializable {
              //made up of unimplemented methods
              protected Object value;
              public Object getCellEditorValue() {
                   return null;
              public void setValue(Object x) {}
              public void setDocument(Object x) {}
              public Document getDocument() {
                   return null;
              public boolean isCellEditable(EventObject anEvent) {
                   return true;
              /** Unfortunately, restrictions on API changes force us to
              * declare this method package private.
              boolean shouldSelectCell(EventObject anEvent) {
                   return true;
              public boolean startCellEditing(EventObject anEvent) {
                   return true;
              public boolean stopCellEditing() {
                   return true;
                   public void cancelCellEditing() {
              public void actionPerformed(ActionEvent e) {
                   fireEditingStopped();
              public void itemStateChanged(ItemEvent e) {
                   fireEditingStopped();
    // Custom Cell Renderer
    * renders a table cell as a JTextPane.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.table.*;
    public class TextPaneRenderer extends JTextPane implements TableCellRenderer                                                  
         * Constructor - just set to noneditable
         public TextPaneRenderer() {
              setEditable(false);
         * implementation of table cell renderer. If the value is a document
         * the, the text panes setDocument is used, otherwise a string value
         * is set
         public Component getTableCellRendererComponent(JTable table, Object value,
                   boolean isSelected, boolean hasFocus, int row, int column) {
              if (value != null)
                   if (value instanceof Document)
                        //set the value to a document
                        setDocument((Document) value);
                   else
                        //convert the value to a string
                        setText(value.toString());
              else
                   //set text to an empty string
                   setText("");
              return this;

    Hi, I came across the forum and found your problem is very similar to what I am having now. Your post has been a year old, I just wonder if you come up anything productive to what you had? Could you let us know what you (or Sun) find out if you do have one? Thanks.

  • Obnoxious JTextPane and JScrollPane problem.

    I have written a Tailing program. All works great except for one really annoying issue with my JScollPane. I will do my best to explain the problem:
    The program will continue tailing a file and adding the text to the JTextPane. When a user scrolls up on the JScrollPane, the program still adds the text to the bottom of the JTextPane and the user can continue to view what they need.
    Here is the problem: I have text being colored throughout the text pane. For instance, the word ERROR will be in red. The problem is when the program colors the text, it moves the scroll pane to the line where word that was colored is at. I don't want that. If the user moves the scroll bar, I want the scroll bar to always stay there. I don't want the program to move to the text that was just colored.
    Is there a way to turn that off? I can't find anything like that anywhere.

    Coloring text will not cause the scrollpane to scroll.
    You must be playing with the caret position or something.
    If you need further help then you need to create a [url http://homepage1.nifty.com/algafield/sscce.html]Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    And don't forget to use the [url http://forum.java.sun.com/help.jspa?sec=formatting]Code Formatting Tags so the code retains its original formatting.

  • Word wrapping incorrect inside JTextPane on MAC 0.5/10.4 and Linux OS

    Hello java-dev team,
    In my application, I am using JTextPane as a text editor to create RTF text. The problem I observed with the JTextPane on MAC OS and Linux OS flavors (I tested on Ubuntu 8.04) is: whenever I am changing any of the text property (font color, font name, font style like bold, italic or underline) and then enter the characters without providing space, the whole word gets wrapped to the next line from the point where exactly the property change starts i.e. the new formatted text is jumped to the next line from the starting point of formatting.
    My requirement is, as I am not adding any space character while changing the property, the characters should be entered in the sequence and should come to new line as per normal word-wrap rule.
    Can anybody help me out in this regards with some solution as it’s a very urgent requirement?
    Below I am also providing the sample code to check the behavior. There is no dynamic facility to change the property in the below code but I am providing the text with multiple formatting settings through code itself. To reproduce the above issue, just type the characters using keyboard in between characters with changed text properties and you can see the whole word jumping to new line.
    import java.awt.Dimension;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.MutableAttributeSet;
    import javax.swing.text.SimpleAttributeSet;
    import javax.swing.text.StyleConstants;
    import javax.swing.text.StyledDocument;
    import javax.swing.text.StyledEditorKit;
    public class TestWrapping {
         JScrollPane scroll;
         JTextPane edit;
         public TestWrapping()  throws Exception {
              final JFrame frame=new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              edit=new JTextPane()
                   public void setSize(Dimension d)
                        if (d.width < getParent().getSize().width)
                             d.width = getParent().getSize().width;
                        super.setSize(d);
                   public boolean getScrollableTracksViewportWidth()
                        return false;
              edit.setPreferredSize(new Dimension(150,150));
              edit.setSize(150,150);
              edit.setEditorKit(new StyledEditorKit());
              scroll=new JScrollPane(edit);
              edit.getDocument().insertString(0,"11111111111111222222222222222222222222222222222222222",null);
              MutableAttributeSet attrs=new SimpleAttributeSet();
              StyleConstants.setBold(attrs,true);
              ((StyledDocument)edit.getDocument()).setCharacterAttributes(30,5,attrs,false);
              StyleConstants.setUnderline(attrs,true);
              ((StyledDocument)edit.getDocument()).setCharacterAttributes(35,5,attrs,false);
              StyleConstants.setFontSize(attrs,25);
              ((StyledDocument)edit.getDocument()).setCharacterAttributes(40,5,attrs,false);
              frame.getContentPane().add(scroll);
              frame.setBounds(0,0,150,150);
              frame.show();
         public static void main(String[] args) throws Exception {
              new TestWrapping();
    }The same functionality works fine on Windows XP and problem is observed on MAC OS 10.4/10.5, Ubuntu 8.04. I am using jdk1.5 on both the platforms. I tested using jdk 6.0 on Ubuntu 8.04, and the problem is easily reproducible. I placed a query in the respective OS forums also but did not receive any replies. I also searched the sun’s bug database, but could not find any bug addressing the mentioned problem correctly. I also logged issue at bugs.sun.com and was assigned internal review ID of 1480019 for this problem.
    If you need any additional information, please let me know.
    Thanks in advance.
    Regards,
    VPKVL

    VPKVL wrote:
    Hi All,
    Just want to update that when I checked this issue with JDK1.6 on Ubuntu 8.04, I am unable to reproduce the issue. Everything works as expected. But problem continues on MAC 10.5. So can anybody help me out in coming out of this issue on MAC 10.5.
    Thanks in advance.The only thing I can suggest is that you open a bug (radar) with apple ( developer.apple.com ), and then wait at least 12 months for Apple to get around to fixing it :s

  • Word wrapping at JTextPane boundaries

    Hi ! I have two problems related to JTextPane -
    1. I want to wrap words which are larger than the width of JTextPane so that it may remain visible inside the fixed boundaries.
    2. if there is an image and it can not be displayed in the same line in continuation of text then it should be displayed in the next line.
    All images that i have used have less width than that of JTextPane.
    Both these problems may be related or different, I dont know how to solve these problems.
    Please suggest any solution.

    Till now I am able to find the height of JTextPane after inserting some text by creating a dummy JTextPane
    and calling the method getPrefferedSize().height
    this wraps text correctly at word boundaries but i want it to be wrapped according to word boundaries and
    textpane boundaries both
    actually I am developing a chat application in which I have to show message from other person
    and if there is some text like ": )", ": D" etc then i want to show smileys :), :D in the place of these substrings
    I can insert text and replace the text with images by using StyledDocument's insert function
    but if i simply replace the text with images then the images are shown in the same line and wrapping doesn't work
    hence some part of images are not visible in the JTextPane
    as shown in the links http://www.facebook.com/photo.php?fbid=193222607456431&set=a.193222600789765.36992.100003060781951&type=1&ref=nf
    and http://www.facebook.com/photo.php?fbid=193225164122842&set=a.193222600789765.36992.100003060781951&type=1&ref=nf
    here link 1 shows the problem of partial display of image
    and link 2 shows the problem of inserting text that is larger than the width of the JTextPane
    And i want that whatever is inside the JTextPane should be shown inside the boundaries of it, I don't want to add a
    horizontal scrollbar !!!!!
    hope you got the problem, please provide some help !

  • Set font color to JTextPane

    I wrote a small program only 70 lines. These codes traverse all the text line by line, show all digits in blue color, but I do not know why, you see, there is something wrong, some characters are not updated correctly. but why?
    import javax.swing.*;
    import java.awt.Color;
    import javax.swing.text.*;
    public class MainWnd extends JFrame{
    private JTextPane textPane = new JTextPane();
    public MainWnd() {
    getContentPane().add(textPane);
    textPane.setText("1234567890\r\n1234567890\r\n1234567890\r\n1234567890\r\n1234567890\r\n");
    setBounds(100, 100, 400, 400);
    formatHighlight(textPane);
    show();
    public void formatHighlight(JTextPane textPane) {
    String text = textPane.getText();
    int begin = 0;
    int end = text.length() - 1;
    System.out.println("First, set all text black color: begin:" + begin + " end:" + end);
    System.out.println("All text is #" + text.substring(begin, end + 1)+"#");
    //reset all as default color black
    setTextColor(textPane, begin, end + 1, Color.BLACK);
    for (int i = begin; i <= end; ) {
    char c = text.charAt(i);
    //digital
    if (Character.isDigit(c)) {
    i = transactDigit(textPane, text, i);
    continue;
    //others
    System.out.println("skip others at i:" + i + " c:" + c);
    i++;
    private void setTextColor(final JTextPane sourcePane,
    final int offset, final int endPos, final Color color) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    MutableAttributeSet attr = new SimpleAttributeSet();
    StyleConstants.setForeground(attr, color);
    if (offset != endPos) {
    StyledDocument doc = (StyledDocument) sourcePane.getDocument();
    doc.setCharacterAttributes(offset, endPos - offset, attr, false);
    private int transactDigit(JTextPane sourcePane, String text, int offset) {
    int endPos = 0;
    for (endPos = offset; endPos < text.length(); endPos++) {
    char c = text.charAt(endPos);
    if (!Character.isDigit(c))
    break;
    System.out.println("set digit blue color from " + offset + " to " + (endPos-1));
    System.out.println("The digit string is #" + text.substring(offset, endPos) + "#");
    setTextColor(sourcePane, offset, endPos, Color.BLUE);
    return endPos;
    public static void main(String[] args) {
    MainWnd mainWnd = new MainWnd();
    Pls, help!

    I have found the reason. replace
    String text = textPane.getText();
    with
    String text = textPane.getDocument().getText(0, textPane.getDocument().getLength());
    It's because the document (model) does not contain '\r', but the view does.
    Thx for your enthusiasm.

  • Double-buffered html JTextPane

    Hi there !
    I am using a JtextPane, displaying a html page, refreshed every second by a thread. This html page changes every second (just a few data). The problem is that the display is flikering and so obnoxious. I tried in vain to make it double-buffered.
    How could I do to fix that ?
    Thx alot.
    Julien

    I'm assuming that you are using the latest version of CVI and NI-DAQ. Then there is a DAQmx example that ships with NI-DAQ that does a Continuous Acquisition with an External Scan Clock and Digital Start Trigger.
    You can find this example in the CVI Folder: ...\CVI70\samples\DAQmx\Analog In\Measure Voltage\Cont Acq-Ext Clk-Dig Start
    Kind regards,
    Karsten
    Applications Engineer
    National Instruments

  • JTextPane and HTML

    My pane is continuing to display the text as plain text instead of html. Why is that?
    JTextPane p=new JTextPane(new HTMLDocument());
    add(p);
    String html="<html><body>TEST</body></html>
    p.setText(html);From what I've learned from the documentation, the pane is initialised with html. When using setText(), the pane still keeps it html style. So, why am I getting plain text???

    If I explicitly use setContentType("text/html") it works.
    But it only works for small html pages. If I use a setText for a page greater than 50k, the page is blank. After that, a getText() results in this:
    <html>
    <head>
    </head>
    <body>
    </body>
    </html>
    Is there a maximum?

  • JTextPane "ghost text": some text is duplicated

    On the surface there is one and only one problem: my JTextPane, which displays a document which is frequently updated (most often using insertString() sometimes displays text twice in two different areas. To be more specific, when new text is insereted it appears as it should, but in addition it can be seen on the line above (the last string ended with a newline). Once this has happened the line continues to accumalate all added text never printing newlines. The text then behaves as expected except that this "ghost text" can not be sellected or edited, its as if it wasn't there!
    This happens infrequently and unexpectedly. More often than not everything renders correctly.
    Possibly related: I sometimes call validate(), setCaretPosition and a few other component methods from threads besides the event thread. This is for good reason though, using invokeLate seems to kill the app completely, and nothing is displayed. The thread is never the main thread.
    Any and all help would be greatlly appreciated!

    This happens infrequently and unexpectedly. More often
    than not everything renders correctly.
    Possibly related: I sometimes call validate(),
    setCaretPosition and a few other component methods
    from threads besides the event thread. This is for
    good reason though, using invokeLate seems to kill the
    app completely, and nothing is displayed. The thread
    is never the main thread.
    Any and all help would be greatlly appreciated!Hard to tell without sample code. But it's very
    likely calling gui code from others threads.
    Use SwingWorker(search the java.sun.com for it).
    Here a link that explains Threads in Swing
    http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html

  • Paint JTextPane on top of table using paintComponent?

    I have a JTable inside a JScrollPane which draws up a grid. In my application the table serves as a background. The best analogy is that this would be much like you might imagine a game board as a background for the game pieces on top.
    The application isn't a game, but to continue using my example, the components or game pieces are represented by JTextPane objects. These components will reside in different locations on top of the table. They can't be rendered within the table because they often span columns and rows. Additionally, even though they always start at the top of a row grid line, they don't necessarily end at the bottom of one.
    So I was wondering if there is a way to manually paint them. I envisioned that I would override the JTable or the JScrollPane paintComponent method but I am not sure how. Here is what I was thinking:
    protected void paintComponent(Graphics g)
    super.paintComponent(g);
    for (JTextPane myComponent : components)
    SwingUtilities.paintComponent(this.getGraphics(), appointmentComponent, this ,
    (int)startingLocation.getX(), (int)startingLocation.getY(),width, height);
    Of course this doesn't work. But is there a way I can draw a JTextPane or any component in an arbitrary location on top of a container of some sort?
    thanks

    Thanks, such a simple solution, I don't know why I didn't start with this, for some reason I decided a layered pane wouldn't work.
    So I added the JLayeredPane as the viewportview of the JScrollPane. Then I added the table to the layered pane and the objects go on the next layer and work great.

  • JTextPane and highlighting

    Hello!
    Here's what I'm trying to do: I have a window that needs to display String data which is constantly being pumped in from a background thread. Each String that comes in represents either "sent" or "recieved" data. The customer wants to see sent and recieved data together, but needs a way to differentiate between them. Since the Strings are being concatinated together into a JTextPane, I need to highlight the background of each String with a color that represents whether it is "sent" (red) or "recieved" (blue) data. Should be easy right? Well, not really...
    Before I describe the problem I'm having, here is a small example of my highlighting code for reference:
         private DefaultStyledDocument doc = new DefaultStyledDocument();
         private JTextPane txtTest = new JTextPane(doc);
         private Random random = new Random();
         private void appendLong() throws BadLocationException {
              String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
              int start = doc.getLength();
              doc.insertString(doc.getLength(), str, null);
              int end = doc.getLength();
              txtTest.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
         private Color randomColor() {
              int r = intRand(0, 255);
              int g = intRand(0, 255);
              int b = intRand(0, 255);
              return new Color(r, g, b);
         private int intRand(int low, int hi) {
              return random.nextInt(hi - low + 1) + low;
         }As you can see, what I'm trying to do is append a String to the JTextPane and highlight the new String with a random color (for testing). But this code doesn't work as expected. The first String works great, but every subsequent String I append seems to inherit the same highlight color as the first one. So with this code the entire document contents will be highlighted with the same color.
    I can fix this problem by changing the insert line to this:
    doc.insertString(doc.getLength()+1, str, null);With that change in place, every new String gets its own color and it all works great - except that now there's a newline character at the beginning of the document which creates a blank line at the top of the JTextPane and makes it look like I didn't process some of the incomming data.
    I've tried in veign to hack that newline character away. For example:
              if (doc.getLength() == 0) {
                   doc.insertString(doc.getLength(), str, null);
              } else {
                   doc.insertString(doc.getLength()+1, str, null);
              } But that causes the 2nd String to begin on a whole new line, instead of continuing on the first line like it should. All the subsequent appends work good though.
    I've also tried:
    txtTest.setText(txtTest.getText()+str);That makes all the text line up correctly, but then all the previous highlighting is lost. The only String that's ever highlighted is the last one.
    I'm getting close to submitting a bug report on this, but I should see if anyone here can help first. Any ideas are much appreciated!

    It may work but it is nowhere near the correct
    solution.It seems to me the "correct" solution would be for Sun to fix the issue, because it seems they are secretly inserting a newline character into my Document. Here's a compilable program that shows what I mean:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.EventQueue;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.util.Random;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextPane;
    import javax.swing.text.BadLocationException;
    import javax.swing.text.DefaultHighlighter;
    import javax.swing.text.DefaultStyledDocument;
    public class TestFrame extends JFrame {
         private JButton btnAppend = new JButton("Append");
         private DefaultStyledDocument doc = new DefaultStyledDocument();
         private JTextPane txtPane = new JTextPane(doc);
         private Random random = new Random();
         public TestFrame() {
              setSize(640, 480);
              setLocationRelativeTo(null);
              addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        dispose();
              getContentPane().add(new JScrollPane(txtPane), BorderLayout.CENTER);
              getContentPane().add(btnAppend, BorderLayout.SOUTH);
              btnAppend.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        doBtnAppend();
         private void doBtnAppend() {
              try {
                   String str = "00 A9 10 20 20 50 10 39 69 FF F9 00 20 11 99 33 00 6E ";
                   int start = doc.getLength();
                    * This line causes all highlights to have the same color,
                    * but the text correctly starts on the first line.
                   doc.insertString(doc.getLength(), str, null);
                    * This line causes all highlights to have the correct
                    * (different) colors, but the text incorrectly starts
                    * on the 2nd line.
    //               doc.insertString(doc.getLength()+1, str, null);
                    * This if/else solution causes the 2nd appended text to
                    * incorrectly start on the 2nd line, instead of being
                    * concatinated with the existing text on the first line.
                    * (a newline character is somehow inserted after the first
                    * line)
    //               if (doc.getLength() == 0) {
    //                    doc.insertString(doc.getLength(), str, null);
    //               } else {
    //                    doc.insertString(doc.getLength()+1, str, null);
                   int end = doc.getLength();
                   txtPane.getHighlighter().addHighlight(start, end, new DefaultHighlighter.DefaultHighlightPainter(randomColor()));
              } catch (BadLocationException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        new TestFrame().setVisible(true);
         private Color randomColor() { return new Color(intRand(0, 255), intRand(0, 255), intRand(0, 255)); }
         private int intRand(int low, int high) { return random.nextInt(high - low + 1) + low; }
    }Try each of the document insert lines in the doBtnAppend method and watch what it does. (comment out the other 2 of course)
    It wastes resources and is inefficient. A lot of work
    goes on behind the scenes to create and populate a
    Document.I tracked the start and end times in a thread loop to benchmark it, and most of the time the difference is 0 ms. When the document gets to about 7000 characters I start seeing delays on the order of 60 ms, but I'm stripping off text from the beginning to limit the max size to 10000. It might be worse on slower computers, but without a "correct" and working solution it's the best I can come up with. =)

  • JTextPane Colour Highlighting

    Im doing up a prototype of a compiler, i have certain keywords like "if"s and "elses" etc etc which i would like to be colour coded differently!!! My problem is when i have big files the time it takes to colour code and display is horrendous!!! I just want to know am i going about the right way in highlighting my keywords?? is there a better way or how can i improve my current code!!! any suggestions at all are welcome!! heres a sample of code..
    public class MyDoc extends DefaultStyledDocument
    static MutableAttributeSet setAttr, ifAttr, defaultAttr;
    public MyDoc()
    setAttr = new SimpleAttributeSet();
    StyleConstants.setForeground(setAttr, Color.red);
    ifAttr = new SimpleAttributeSet();
    StyleConstants.setForeground(ifAttr, Color.blue);
    defaultAttr = new SimpleAttributeSet();
    StyleConstants.setForeground(defaultAttr, Color.black);
    public void insertString(int offs, String str, AttributeSet a) throws
    BadLocationException
    if (str == null) return;
    StringTokenizer tokenizer = new StringTokenizer(str," \n",true);
    try
    while( tokenizer.hasMoreTokens())
    String token = (String)tokenizer.nextElement();
    if(token.length() == 0)
    continue;
    if (token.compareTo("set") == 0)
    super.insertString(offs, token, setAttr);
    } else if (token.compareTo("if") == 0)
    super.insertString(offs, token, ifAttr);
    } else
    super.insertString(offs,token, defaultAttr);
    offs = offs + token.length();
    } catch (BadLocationException ble)
    System.err.println("MyDoc::insertString()"+ble.toString());
    }catch(Exception e)
    System.err.println("MyDoc::insertString()"+e.toString());
    bottom line is that im looking for some other way, more elegant way of getting keywords highlighted, the above is nasty!!!
    cheers people,
    JB.

    I have tried a couple of different approaches for using threads:
    1) Load the data into the text pane and then use a thread for highlighting. The highlighting got messed up if you type data in the text pane while the highlighting thread is working. This approach won't work with the current structure of the SyntaxDocument.
    2) Load data into the text pane in smaller pieces. This approach shows a little more promise as the text pane is shown with initial data in a couple of seconds. However, the entire load time goes from 15 to 26 seconds. During this 26 second load time you can type data and scroll, but the text pane reacts very slowly. I haven't verified that data inserted into the document by typing does not cause problems with data being loaded into the document by the background thread. (Swing components are not thread safe, but hopefully insertion of data into the document is). Here is the test class:
    import java.awt.*;
    import java.io.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class LoadTextPane extends JFrame
         char[] data;
         JTextPane textPane;
         public LoadTextPane(String fileName)
              EditorKit editorKit = new StyledEditorKit()
                   public Document createDefaultDocument()
                        return new SyntaxDocument();
              textPane = new JTextPane();
             textPane.setEditorKitForContentType("text/java", editorKit);
             textPane.setContentType("text/java");
              JScrollPane sp = new JScrollPane(textPane);
              getContentPane().add( sp );
              long startTime = new Date().getTime();
              try
                   File f = new File( fileName );
                   FileReader in = new FileReader( f );
                   int size = (int) f.length();
                   data = new char[ size ];
                   int chars_read = 0;
                   while( chars_read < size )
                        chars_read += in.read( data, chars_read, size - chars_read );
                   in.close();
                   long endTime=new Date().getTime();
                   System.out.println( "File size: " + chars_read );
                   // System.out.println( data );
              catch (IOException sse)
                   System.out.println("Error has occured"+sse);
              System.out.println( "Time to read file: " + (new Date().getTime() - startTime ));
              if (data.length > 8092)
                   Thread load = new LoadThread(data, textPane.getDocument());
                   load.start();
              else
                   textPane.setText( new String(data, 0, data.length) );
         public static void main( String[] args )
              String fileName = "c:/java/jdk1.3/src/java/awt/Component.java";
              JFrame f = new LoadTextPane(fileName);
              f.setDefaultCloseOperation( EXIT_ON_CLOSE );
              f.setSize( 1000, 600);
              f.setVisible(true);
         class LoadThread extends Thread
              char[] data;
              Document doc;
              LoadThread(char[] data, Document doc)
                   this.data = data;
                   this.doc = doc;
              public void run()
                  int start = 0;
                  int end = data.length;
                  int increment = 8192;
                   long begin = System.currentTimeMillis();
                  while ( start < end )
                       if (start + increment > end)
                            increment = end - start;
                       String text = new String(data, start, increment);
                       try
                            doc.insertString(doc.getLength(), text, null);
                       catch(BadLocationException e)
                            System.out.println(e);
                       start += increment;
                        //  allow some time for the gui to process typed text, scrolling etc
    //                    try { Thread.sleep(300); }
    //                    catch (Exception e) {}
                   System.out.println( "Load Text Pane: " + (System.currentTimeMillis() - begin) );
    }

  • JTextPane flicker insanity

    Hello
    I am having a terrible time with flicker in a JTextPane within a JScrollPane.
    I am using JTextPane (_tp) with DefaultStyledDocument (_doc) for formatting.
    I am adding lines of data to the end of the pane and I need the data to continue to scroll so I use JTextPanes setCaretPosition method to move the insertion point to the end of the document.
    I use _doc.insertString to display data.
    I have been searching the forum for cures to my ailment, however, all attempts to fix this problem have come up empty.
    I have tried setting the JTextPane visibility to false, update display, then set the JTextPane back to visible.
    I have tried writing to temporary document then displaying the temp document.
    I have tried using SwingUtilities.invokeLater though I'm not yet familiar with how it really works.
    The basic of the code:
    public void updateTextArea(String data) {
    _tp.setEditable(true);
    try
    doc.insertString(doc.getLength(), data + "\n", _style);
    } catch (BadLocationException e){}
    if (_tp.getCaretPosition() != _doc.getLength())
         tp.setCaretPosition(doc.getLength());
    _tp.setEditable(false);
    I'm out of ideas. Any suggestions or tips would be helpful.
    Thanks for your time.
    BV     

    I would expect quite a lot of flicker in any sequence
    such as:
    _tp.setVisible(false);
    _tp.setVisible(true);How does the UI behave if you don't hide/show the text
    field?You are absolutely correct! Toggling the visible like that was a mistake.
    And through many, many trials and errors I did find the problem that I was having.
    I was trying to fix the problem with the JTextPane and Document. However, the solution was actually in the JScrollPane. I simply had to setDoubleBuffered(true) for the JScrollPane and it fixed the flicker.
    Thanks!!

  • JTextPane && JScrollPane

    Hi everybody,
    maybe this question, which marks me as very dumb, but I will try.
    I created a JTextPane with all the needed things(Styles,...) and everything works fine.
    But now I want to embedd this pane into a JScrollPane. It works fine too, except of the horizontal scrollbar.
    If I force its visibility it is shown, but nothing happens when the current line in the textpane will become longer than the displayable area. What I mean is, that the scrollbar displays, but the bubble will not appear. Therefore the current line will be continued in the next line.
    But I just want this text to be continued in the same line, so that I can scroll.
    thanks in advance
    regards
    c

    its strange, you have to add an additional viewport into the viewport of the scrollpane. I thought the viewport of the scrollpane should do the job. why doesnt it do so?
    regards,
    stefan
    Hi,
    ok some hints
    1. create a viewport
    2. add the JTextPane to this viewport
    3. add the viewport to a JScrollPane
    // ... some code
    JViewport vp = new JViewport();
    vp.add(textPane);
    vp.setScrollMode(JViewport.BLIT_SCROLL_MODE);
    // ... maybe some more code
    JScrollPane sp=new JScrollPane(vp,
    JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
    JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);hope it helps
    regards

Maybe you are looking for

  • CE:  An internal authentication error has occurred

    Could anyone help me please? i have been play 'try and search game':( for serveral days for this problem. i search this forum and find other people have been in same problem, but no progress for me i look around at uwc.log, but doesn't give me clue,

  • Apex 3.1.2 - missing column in CSV output

    Hi, We recently moved our application to apex 3.1.2. There is a report with a CSV output that worked fine in apex 3.0. With the same report in apex 3.1.2, one column is missing in the CSV file but is showing on the report. Show column is set to YES,

  • Help on KO22 - BDC Update - Very Urgent

    Dear Gurues, Im writing a program for mass update the Budget Price in Transaction Code KO22 using a BDC. I have complete my codings but,when i execute in foreground i found that the amount is not updated in the field.I belived is something wrong with

  • Creating cursor using Execute immediate

    I am trying to create one cursor using a for loop, but I am not able to do so, could you please help me with the approach to get it done. Here is the scenario: I have one table table_1,it contains 2 columns source_query , target_query. source_query a

  • I show full wifi signal but pages won't load

    I recently upgraded to Lion and I'm having internet connectivity problems. On my new macbook it shows I have full signal to my secured personal wifi network but nothing loads up on safari. This problem wasn't present when I was using Snow Leopard. My