( (JTextPane in JScrollPane) in JTabbedPane)???

JTextPane textarea = new JTextPane();
JScrollPane scroll= new JScrollPane(textarea);
JTabbedPane tab = new JTabbedPane();
tab.add(scroll);
Now the problem is when i create many tabs and put
it in my window , and i want to jump from one tab to
another , the textpane does not get the focus .
tab contains scroll as its client so it gives focus to the
scroll but i want the textarea to have the cursor.so that there is no need for the user to click in the textarea to gain focus.
I hope some one understands my problem and helps me ...
thanks alot......

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

  • Trouble Scrolling down(JTextPane inside JScrollPane)

    I am writting a java interface to the Jabber IM system. I'm trying to allow html in the messages, so I have a JTextPane that I use to show what has been said. In order to scroll, I've placed the JTextPane within a JScrollPane. When a new message needs to be placed into the JTextPane, I set the JTextPane to the proper text and set the scroll bar from the scroll pane to it's .getMaximum() value. My problem is that the .getMaximum() function only gets the NEW, ACTUAL maximum AFTER the JTextPane has been parsed and painted into the JPanel. The time it takes to do this is proportional to the length of the text within the JText pane and relative to the speed of the computer. So, the scroll bars should be done in response to the completion of the painting of the JTextPane instead of a set time delay. I don't know how to do this. I assume I need to overwrite some paint or repaint function, but I don't know which one to overwrite. The JTextPane is in a JScrollPane in a JSplitPane in a JPanel in a JFrame, if that helps at all.
    I've been stuck on this forever..
    Thanks for any help.

    Gave you 6 $. JTextPane doesn't have the insert function, so I've been using setText(). The problem is that the second the Pane is redrawn, it shows the top of the document, then scrolls to the bottom. This takes a fraction of a second, but still is undesireable.
    What I'm trying to do is make a new textpane object, set the text, set the caret position, THEN replace the old pane. The problem is, I can't just use oldPane = newPane because that just makes oldPane reference the new Object.(The object shown is then only referenced from the parent swing component, a JScrollPane) I've tried using the .setViewportView on the JScrollPane that the JTextPane is within, but then it doesn't scroll to the caret position.
    I've gotten it to work once. I had created all new objects(JTextPane within JScrollPane within JSplitPane within JPanel) adding each to it's parent and adding the JPanel to the container. This worked ONCE! I changed the code, then changed it back and it didn't work again...
    Here's the code I have for buffering the JTextPane.
    if(chatPane == chatPaneBuffer2){
    chatPaneBuffer1.setText(chatStringBuffer.toString());
    chatPaneBuffer1.setCaretPosition(chatPaneBuffer1.getDocument().getLength());
    chatPane = chatPaneBuffer1;
    }else{
    chatPaneBuffer2.setText(chatStringBuffer.toString());
    chatPaneBuffer2.setCaretPosition(chatPaneBuffer2.getDocument().getLength());
    chatPane = chatPaneBuffer2;
    This works, but somehow I need the object chatPane is pointing at to be referenced by my JScrollPane.

  • JTextPane inside JScrollPane

    Hi,
    I've seen a lot of possibilities to get a JTextPane into JScrollPane without wraping the text in the forum. None worked for me..
    My situation:
    JTextPane(editable=false) with given text(DefaultStyledDocument) is inside JScrollPane.
    I replace (by pressing a button) some text parts with longer text AND JTextPane wraps it!..
    I tried to set the size of the textPane to the computed line width of the longst line, but nothing happened.. (I expected the JScrollPane to show off horizontal scrollbar, because the width of JTextPane is getting bigger than the width of JScrollPane).
    Anyone knows how to put formatted text into text- or scrollpane without wraping it?
    And who allowed JTextPane to wrap my lines anyway?!
    (it's called StyledDocument and not ChaosDocument :)
    Thanks in advance!
    Raman.

    Not sure that JTextPane is the best place to start. The wrapping is controlled by ParagraphView and its underlying structure. Try looking at implementing extensions to the standard EditorKit/ViewFactory to tweak this behaviour

  • 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.

  • JTextPane in JScrollPane... Scrolling when needed

    Hello all.
    I have a jtextpane in a jscrollpane and I'm using the following code to append a line in jtextpane and set the vertical scrollbar of jscrollpane at the bottom...
      htmlDoc = (HTMLDocument) output.getDocument();
      htmlKit.insertHTML(htmlDoc, htmlDoc.getLength(), s, 0, 0, null);
      output.setCaretPosition(htmlDoc.getLength());where output is the jtextpane.
    My problem is that, if the user manually changes the position of the vertical scrollbar, after appending a new line in jtextpane, the above code will set the scrollbar at the bottom.
    Is it possible to keep the scrollbar at the position it was before the new line has been appended (if the position of the scrollbar has been changed)?
    Thanks in advance,
    Charalampos

    StanislavL... with your suggestion the scroll bar will never scroll to the bottom.
    I want to place the scroll bar at the bottom if it was at the bottom before I append text to jtextpane, otherwise I want to leave the scroll bar at the same position it was before I append the text.

  • Problem about using JTextPane in JScrollPane

    I put a JTextPane in a JScrollPane.
    But when I reduce the window size of the JScrollPane with my mouse, the text line in the JTextPane is broken to newlines automatically due to the reduced window size.
    How to prevent the text lines breaking in this situation!

    OK, so the words are wrapping when they're not suppose to. How are you adding your JTextPane to the JScrollpane? Also, does setting a preferred size or a minimum size on the JTextPane help?
    That's an odd problem. In looking at the API I see that JTextArea and JTextPane are both derived (eventually) from JTextComponent. But the line wrap option is only in JTextArea. This makes me think that it would be possible to overload paint method of the JTextPane. But wow! That would be messy.
    I'll keep thinking about it. Let us know if you find a solution.

  • Help:Jtextpane in Jscrollpane , the vertical scroll bar  at bottom

    Immediate help needed if possible.
    The scrollpane that contains the textpane is showing the vertical bar at the bottom of the page even if use :-
    scrollRectToVisible(new Rectangle(0,0,1,1));
    Here is my code:-------------------------
    JPanel panel = new JPanel();
    JTextPane textPane = createTextPane();
    textPane.setEditable(false);
    textPane.scrollRectToVisible(new Rectangle(0,0,1,1));
    JScrollPane paneScrollPane = new JScrollPane(textPane);
    paneScrollPane.setPreferredSize(new Dimension(525, 285));
    paneScrollPane.setMinimumSize(new Dimension(14, 48));
    gc.addCentered(paneScrollPane);
    add ( panel );

    From
    http://search.java.sun.com/search/java/index.jsp?qp=&nh=10&qt=%2Btitle%3Ajtextpane+%2Btitle%3Atop&col=javaforums
    scrollRectToVisible(new Rectangle(0,0,1,1))

  • Put JScrollPane inside JTabbedPane

    Thanks alot for helping me
    i have a JTabbedPane inside it a static panel but i insert in it a new resizing JPanel but when i want to resize the inner panel the scroll bars are not shown
    the code below
    tabs = new JTabbedPane();
                             tabs.setTabPlacement(JTabbedPane.BOTTOM);
                             JPanel panel = new JPanel();
                             panel.setLayout(null);
                             panel.setBackground(Color.white);
                             drawingPanel = new DrawingPanel();
                             drawingPanel.setBounds(Statics.getWidth(20),Statics.getHeight(20),Statics.getWidth(450),Statics.getHeight(430));
                             panel.add(drawingPanel);
    notice that drawing panel is a class that extends JPanel

    You have to create a JScrollPane:
    DrawingPanel drawingPanel = new DrawingPanel();
    drawingPanel.setBounds(Statics.getWidth(20),Statics.getHeight(20),Statics.getWidth(450),Statics.getHeight(430));
    JScrollPanel scrollPane = new JScrollPane(drawingPanel);Now you have a scrollPane for your drawing panel. Put the scrollPane on your JTabbedPane.

  • JTextPane inside JScrollPane resizing when updated

    Hiya all,
    I've been struggling with this problem and checking the forums, but didn't find a solution, so I hope someone can help...at least help me for the nice picture :) It has to do with JTextPane's automatically resizing to their content on a GUI update, rather than scrollbars appearing (the desired result).
    Basically, I have a scenario where I am creating a series of multiple choice answers for a question. Each answer consists of a JTextPane inside a JScrollPane, and a JRadioButton, which are all contained in a JPanel (called singleAnswerPanel). So for 2 answers, I would have 2 of these singleAnswerPanels. There is a one large JPanel that contains all the singleAnswerPanels (called allAnswersPanel). This allAnswersPanel is contained in a JScrollPane. Graphically, this looks like:
       |       JPanel (allAnswersPanel) inside a JScrollPane            |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
       |                                                                |
       |  ------------------------------------------------------------  |
       | |     JPanel (singleAnswerPanel)                             | |
       | |    ----------------------------------                      | |
       | |   |  JTextPane inside a JScrollPane  |     * JRadioButton  | |
       | |    ----------------------------------                      | |
       | |                                                            | |
       |  ------------------------------------------------------------  |
       |                                                                |
        ----------------------------------------------------------------So above, I show 2 answers that can be filled in with text. So assuming both answer JTextPanes are filled with text beyond their current border (scrollbars appear as expected) and the user wishes to add more answers. I have a button to add another singleAnswerPanel to the containing JPanel (allAnswersPanel), and then I validate the main JScrollPane that contains the allAnswersPanel as it's view. The problem that occurs is the existing single answer JTextPanes resize to the size of their text and the vertical scrollbars (only vertical ones setup) of the JTextPanes dissappear! My intent is to keep the existing JScrollPanes the same size (with their scrollbars) when a new answer is added.
    The code snippet below shows what gets done when a new answer is added:
    private void createAnswer()
        // The panel that will hold the new single answer JTextPane pane
        // (inside a JScrollPane) and radio button.
        JPanel singleAnswerPanel = new JPanel();
        // Create the text pane for the single answer.
        JTextPane singleAnswerTextPane = new JTextPane();
        Dimension dimensions = new Dimension(200, 30);
        singleAnswerTextPane.setPreferredSize(dimensions);
        singleAnswerTextPane.setMaximumSize(dimensions);
        // Create a scroll pane and add the single answer text pane.
        JScrollPane singleAnswerScrollPane =
         new JScrollPane(singleAnswerTextPane);
        // Create a radio button that is associated with the single
        // answer text pane above.
        JRadioButton singleAnswerRadioButton = new JRadioButton();
        // Add the scroll pane and radio button to the panel (for a single
        // answer).
        singleAnswerPanel.add(singleAnswerScrollPane);
        singleAnswerPanel.add(singleAnswerRadioButton);
        // Add the panel holding a single answer to the panel holding
        // all the answers.
        m_allAnswersPanel.add(singleAnswerPanel);
        // Update the display.  m_allAnswersScrollPane is a JScrollPane
        // that has the m_allAnswersPanel (JPanel) as its view.
        m_allAnswersScrollPane.validate();
    }     Sorry for the length of the message, but I really want to solve this problem. So again, when updating the JScrollPane with validate(), the JTextPane for a single answer resizes to it's contents (plain text currently) and loses it's vertical scrollbars, but I want it to stay the same size and maintain the scrollbars.
    Thanks!

    http://java.sun.com/docs/books/tutorial/uiswing/mini/layout.htmlimport javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    public class Test extends JFrame {
        int cnt=0;
        Random r = new Random();
        String[] nouns = {"air","water","men","idjits"};
        JPanel mainPanel = new JPanel(new GridBagLayout());
        JScrollPane mainScroll = new JScrollPane(mainPanel);
        JScrollBar mainScrollBar = mainScroll.getVerticalScrollBar();
        public Test() {
         setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
         Container content = getContentPane();
         content.add(new JLabel("QuizMaster 2003"), BorderLayout.NORTH);
         content.add(mainScroll, BorderLayout.CENTER);
         JButton jb = new JButton("New");
         content.add(jb, BorderLayout.SOUTH);
         jb.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent ae) {
              JPanel questionPanel = new JPanel(new GridBagLayout());
              questionPanel.add(new JLabel("Question "+cnt++),
                   new GridBagConstraints(0,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              questionPanel.add(new JLabel("Why is there "+
                            nouns[r.nextInt(nouns.length)]+"?"),
                   new GridBagConstraints(1,0,1,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.NONE,
                        new Insets(1,2,1,2),0,0));
              JTextArea jta = new JTextArea();
              JScrollPane jsp = new JScrollPane(jta);
              jsp.setPreferredSize(new Dimension(300,50));
              questionPanel.add(jsp, new GridBagConstraints(0,1,2,1,0.0,0.0,
                        GridBagConstraints.EAST, GridBagConstraints.BOTH,
                        new Insets(1,2,1,2),0,0));
              mainPanel.add(questionPanel, new GridBagConstraints(0,cnt,1,1,0.0,0.0,
                            GridBagConstraints.EAST,GridBagConstraints.NONE,
                            new Insets(0,0,0,0),0,0));
              mainPanel.revalidate();
              mainScroll.getViewport().setViewPosition(new Point(0, mainPanel.getHeight()));
         setSize(400,300);
         show();
        public static void main( String args[] ) { new Test(); }
    }

  • JTabbedPane and JScrollPane problem

    Hi all,
    I'm trying to make working JScrollPane into JTabbedPane. I have been trying several times to make it but with no acceptable effects :( I attached below the simple code to show what I'm interested in.
    PANEL1 has its dimension. I'd like to make that the JScrollPane will be active and enabled to roll when user change JFrame size to less than PANEL1 on pane1.
    Please help!
    Thanks for everyone,
    Greetings,
    import java.lang.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class Sample     {
    static JFrame fr;
    static JPanel pane1, pane2, pane3;
    static JLabel AAA, BBB, CCC;
    static JPanel PANEL1;
    static JTabbedPane panel;
    public static void main(String args[])     {
              fr = new JFrame("Sample");
              pane1 = new JPanel();
              pane1.setLayout(null);
              pane2 = new JPanel();
              pane2.setLayout(null);
              pane3 = new JPanel();
              pane3.setLayout(null);
              panel = new JTabbedPane();
              Font myfont1 = new Font("SansSerif",0,20);
              Font myfont2 = new Font("SansSerif",0,15);
              Font myfont3 = new Font("SensSerif",1,15);
              AAA = new JLabel("AAA");
              BBB = new JLabel("BBB");
              CCC = new JLabel("CCC");
              AAA.setFont(myfont2);
              BBB.setFont(myfont2);
              CCC.setFont(myfont2);
              AAA.setBounds(20,20,300,20);
              BBB.setBounds(20,50,300,20);
              CCC.setBounds(20,80,300,20);
              PANEL1 = new JPanel();
              PANEL1.setLayout(null);
              PANEL1.setBackground(java.awt.Color.CYAN);
              PANEL1.setBounds(20,15,250,300);
              PANEL1.add(AAA);
              PANEL1.add(BBB);
              PANEL1.add(CCC);
              pane1.add(PANEL1);
              panel.insertTab("A", null, pane1, null, 0);
              panel.setSelectedIndex(0);
              panel.insertTab("B", null, pane2, null, 1);
              panel.setSelectedIndex(0);
              panel.insertTab("C", null, pane3, null, 2);
              panel.setSelectedIndex(0);
              panel.setBounds(0,0,550,450);
              fr.setLayout(null);
              //fr.setResizable(false);
              fr.setBackground(java.awt.Color.CYAN);
              fr.setForeground(java.awt.Color.CYAN);
              fr.add(panel);
              fr.pack();
              fr.setSize(550, 450);
              fr.setLocationRelativeTo(null);
              fr.setVisible(true);
    }

    Unfortunately no :( Besides, I can't understand at
    all this line:
    JTabbedPane (panel)TabbedPane = ... new
    w JTabbedPane(...).add/insertTab( ... new
    JScrollPane(new JPanel(...)) ... )It's to big cut-off like for me. Can you insert it
    into my Sample?
    Regards and thanks,It's only my "dev speak". Put a ";" and a var name (, ...) whereever needed, and remove some"()".
    (Sorry, normally I don't help dev beginners on so more complex problems, with just an easy answer.)

  • JTextPane/JScrollPane problems

    in my JTextPane i would like to be able to set the tab size (like you can with JTextArea), and for some reason my JScrollPane doesn't want to scroll the JTextPane horizontally, it just wraps the text. any help and sample code is very appreciated.
    TravenE

    Well normally I'd tell you to search the forums because I've answered both of these question several times before. But since the search isn't currently working for me I'm assuming it isn't working for you either, so here are my suggestons.
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TextPaneTabs extends JFrame
         public TextPaneTabs()
              JTextPane textPane = new JTextPane();
              textPane.setFont( new Font("monospaced", Font.PLAIN, 12) );
              JScrollPane scrollPane = new JScrollPane( textPane );
              scrollPane.setPreferredSize( new Dimension( 200, 200 ) );
              getContentPane().add( scrollPane );
              setTabs( textPane, 4 );
         public void setTabs( JTextPane textPane, int charactersPerTab)
              FontMetrics fm = textPane.getFontMetrics( textPane.getFont() );
              int charWidth = fm.charWidth( 'w' );
              int tabWidth = charWidth * charactersPerTab;
              TabStop[] tabs = new TabStop[10];
              for (int j = 0; j < tabs.length; j++)
                   int tab = j + 1;
                   tabs[j] = new TabStop( tab * tabWidth );
              TabSet tabSet = new TabSet(tabs);
              SimpleAttributeSet attributes = new SimpleAttributeSet();
              StyleConstants.setTabSet(attributes, tabSet);
              int length = textPane.getDocument().getLength();
              textPane.getStyledDocument().setParagraphAttributes(0, length, attributes, false);
         public static void main(String[] args)
              TextPaneTabs frame = new TextPaneTabs();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.text.*;
    public class TestNoWrap extends JFrame
         JTextPane textPane;
         JScrollPane scrollPane;
         public TestNoWrap()
              JPanel panel = new JPanel();
              panel.setLayout( new BorderLayout() );
              setContentPane( panel );
              // no wrap by adding text pane to a panel using border layout
              textPane = new JTextPane();
              textPane.setText("1234567890 1234567890 1234567890");
              JPanel noWrapPanel = new JPanel();
              noWrapPanel.setLayout( new BorderLayout() );
              noWrapPanel.add( textPane );
              scrollPane = new JScrollPane( noWrapPanel );
              scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
              panel.add( scrollPane, BorderLayout.NORTH );
              // no wrap by overriding text pane methods
              textPane = 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;
              textPane.setText("1234567890 1234567890 1234567890");
              scrollPane = new JScrollPane( textPane );
              scrollPane.setPreferredSize( new Dimension( 200, 100 ) );
              panel.add( scrollPane );
         public static void main(String[] args)
              TestNoWrap frame = new TestNoWrap();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • How to change the size of the caret in a JTextPane

    I have text of different font sizes and the default caret height is the height of the text with the maximum font size. How do I change the caret height so that it matches the height of the text with the specified font size ?

    This has been a real pain in the butt to figure out, but I think I finally got it. If you create your own caret (subclass of DefaultCaret) then you override its paint() and damage() methods. I was having all kinds of problems with this though. I was getting pieces of carets left behind when I moved with the arrow keys, etc... from the helps I found. The arrow keys were my big problem.
    I think I finally figured out that the damage() simply does need to specify an area a little bigger than the old caret so it can blank it out. Then I think others had a logic problem, and Sun does not make this problem clear. What happens it that I think repaint() calls paint() who then uses the bigger x, y, height and width parameters that got set in damage(), which was causing my problems because the damage size was bigger than the size I wanted to create my caret with. What I do is figure out my area from the font I am using (another trick) and make them (the charWd and charHt) variables class variables. I calculate them in damage, use a bigger area to blank out my old caret in damage, and then used the correct caret size I calculated in damage() in paint(), instead of the rectangle values that seem to get passed from damage() to paint(). That was the problem in other examples.
    Here is my code:
    run with java caretPain
    run with java caretPain -1 to see my fixed version
    run with java caretPain -2 to see some problems
    // written by: Stan Towianski
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Hashtable;
    import java.util.ArrayList;
    import javax.swing.*;
    import javax.swing.text.*;
    import javax.swing.event.*;
    import javax.swing.undo.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.text.*;
    import javax.swing.plaf.*;
    import java.net.URL;
    import java.io.*;
    import java.beans.*;
    public class caretPain extends JFrame {
    static caretPain CRTP2;
    JPanel contentPane;
    JTextPane textPane;
    JTextPane textPane2;
    JScrollPane scrollPane;
    JSplitPane splitPane;
    String newline = "\n";
    static final int MAX_CHARACTERS = 300100;
    static int FrameWidth = 500;
    static int FrameHeight = 300;
    String caretType = "blockOutline";
    static int useSpecialCaret = 0;
    DefaultCaret useCaret = new MyCaret();
    public caretPain() {
    textPane = new JTextPane( new DefaultStyledDocument() );
    textPane2 = new JTextPane( new DefaultStyledDocument() );
    if ( useSpecialCaret == 1 )
    System.out.println( "using special caret 1" );
    textPane.setCaret( useCaret );
    else if ( useSpecialCaret == 2 )
    System.out.println( "using special caret 2" );
    textPane.setCaret( new WsCaret() );
    textPane.setCaretPosition(0);
    textPane.setMargin(new Insets(5,5,5,5));
    scrollPane = new JScrollPane(textPane);
    textPane.setPreferredSize(new Dimension(FrameWidth, FrameHeight));
    JScrollPane scrollPane = new JScrollPane(textPane);
    //Create a split pane for the change log and the text area.
    splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
    textPane, textPane2 );
    splitPane.setOneTouchExpandable(true);
    //Add the components to the frame.
    contentPane = new JPanel(new BorderLayout());
    contentPane.add(splitPane, BorderLayout.CENTER);
    setContentPane(contentPane);
    class MyCaret extends DefaultCaret
    int charWd = 30;
    int charHt = 30;
    // draw the caret
    public void paint(Graphics g)
    System.err.println( "entered MyCaret.paint()" );
    if ( ! isVisible() )
    System.err.println( "exiting because not visible" );
    return;
    try {
    JTextComponent c = getComponent();
    int dot = getDot();
    Rectangle r = c.modelToView(dot);
    System.err.println("caret: text position: " + dot +
    ", view location = [" +
    r.x + ", " + r.y + "]" +
    newline);
    g.setColor(c.getCaretColor());
    //g.drawLine(r.x, r.y + r.height - 1, r.x + 14, r.y + r.height - 1);
    System.err.println( "caretType =" + caretType ); //+ " component =" + c.toString() );
    if ( caretType.equals( "blockOutline" ) )
    g.drawRect( r.x, r.y, charWd, charHt );
    else if ( caretType.equals( "block" ) )
    g.fillRect( r.x, r.y, charWd, charHt );
    else if ( caretType.equals( "bar" ) )
    g.drawLine( r.x, r.y, r.x, r.y + charHt );
    catch (BadLocationException e) {
    System.err.println( "bad caret loc" + e);
    // specify the size of the caret for redrawing
    // and do repaint() -- this is called when the
    // caret moves
    //protected synchronized void damage(Rectangle r)
    public synchronized void damage(Rectangle r)
    System.err.println( "entered MyCaret.damage()" );
    System.err.println("caret.damage(): text position: " + getDot() +
    ", view location = [" +
    r.x + ", " + r.y + "]" +
    newline);
    //FontMetrics fm = g.getFontMetrics();
    //System.out.println( "textPane getfont =" + textPane.getFont() );
    //System.out.println( "\n\n read in attribs font size =" + textPane.getInputAttributes().getAttribute(StyleConstants.FontSize) + "\n\n" );
    //int ii = Integer.parseInt( (String) textPane.getInputAttributes().getAttribute( StyleConstants.FontSize ) );
    int ii = Integer.parseInt( String.valueOf( textPane.getInputAttributes().getAttribute( StyleConstants.FontSize ) ) );
    //System.out.println( "textPane input attrib font size =" + ii );
    Font f = new Font( "ff", Font.PLAIN, ii );
    //System.out.println( "textPane input attrib font =" + f );
    FontMetrics fm = getFontMetrics( f );
    //FontMetrics fm = g.getFontMetrics();
    //FontMetrics fm = getFontMetrics( textPane.getInputAttributes().getAttribute( StyleConstants.FontSize ) );
    //MutableAttributeSet inputAttributes = getInputAttributes();
    //String fs = textPane.getAttribute( "FontSize" );
    //System.out.println( "\n\n read font size =" + textPane.getCharacterAttributes().getAttribute(StyleConstants.FontSize) + "\n\n" );
    charWd = fm.charWidth( 'k' );
    charHt= fm.getHeight();
    //System.out.println( "font width =" + charWd + " font height =" + charHt + " font =" + fm.toString());
    if ( r == null )
    System.err.println( "caret.damage() return on rectangle == null" );
    return;
    x = r.x - 2;
    y = r.y - 2; // + r.height - 2;
    width = charWd + 4; //textPane.getColumnWidth();
    height = charHt + 4; //textPane.getRowHeight();
    System.err.println("caret.damage(): set caret width, height, x, y =" + width + "," + height + "," + x + "," + y );
    repaint();
    //repaint();
    public class WsCaret extends DefaultCaret {
    transient private int[] flagXPoints = new int[3];
    transient private int[] flagYPoints = new int[3];
    public WsCaret() {
    this.setBlinkRate(500);
    public void paint(Graphics g) {
    if(isVisible()) {
    JTextComponent component = this.getComponent();
    TextUI mapper = component.getUI();
    Rectangle r = null;
    try {
    r = mapper.modelToView(component, this.getDot());
    catch(BadLocationException exc) {}
    //System.out.println( "rect r =" + r.toString() );
    //g.drawLine(r.x, r.y, r.x, r.y + r.height - 1);
    //g.drawLine(r.x+1, r.y, r.x+1, r.y + r.height - 1);
    g.drawRect( r.x, r.y, 10, r.height );
    Document doc = component.getDocument();
    if (doc instanceof AbstractDocument) {
    Element bidi = ((AbstractDocument)doc).getBidiRootElement();
    if ((bidi != null) && (bidi.getElementCount() > 1)) {
    // there are multiple directions present.
    flagXPoints[0] = r.x;
    flagYPoints[0] = r.y;
    flagXPoints[1] = r.x;
    flagYPoints[1] = r.y + 4;
    flagYPoints[2] = r.y;
    flagXPoints[2] = (true) ? r.x + 5 : r.x - 4;
    System.out.println( "going g.fillPolygon" );
    g.fillPolygon(flagXPoints, flagYPoints, 3);
    protected synchronized void damage(Rectangle r) {
    if (r != null) {
    this.x = r.x - 4;
    this.y = r.y;
    //there must be a better way to doing this, but for now you
    //just increase the width so that it will cover the new caret's size
    this.width = 20; // the original width is 10
    this.height = r.height;
    //this.height = r.height + 20;
    //this.height = 10;
    repaint();
    //The standard main method.
    public static void main(String[] args) {
    if ( args.length > 0 )
    System.out.println( "found arg so will use special caret." );
    if ( args[0].equals( "-1" ) )
    useSpecialCaret = 1;
    else if ( args[0].equals( "-2" ) )
    useSpecialCaret = 2;
    else
    System.out.println( "found no arg so will standard caret." );
    System.out.println( "give arg: -1 to get Stan\'s working caret" );
    System.out.println( "give arg: -2 to get another example\'s caret" );
    try
    CRTP2 = new caretPain();
         catch (Exception ex)
    System.out.println("Error creating CRTP2: " + ex);
    ex.printStackTrace();
    System.exit(0);
    CRTP2.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    public void windowActivated(WindowEvent e) {
    CRTP2.textPane.requestFocus();
    CRTP2.setTitle( "This is my title you" );
    CRTP2.pack();
    CRTP2.setVisible(true);

  • Word Wrap in JTextPane

    I'm working with just a JTextPane, no JScrollPane around it or anything.
    I would like the JTextPane to use word wrap, but it looks like by default it does not. I looked through some API stuff and tutorials and found nothing on the subject.
    The code is trivial and pointless to post right now. All I dd was make a JTextPane via new JTextPane() (no arguments or anything) and type in it enough to see if it word wrapped and it didn't.
    Is there a way to enable word wrap on JTextPanes?

    no JScrollPane around it or anything.The scroll pane forces the wrapping because it enforces the width limit. Otherwise there is no limit.
    You can use setPreferredSize(...) to force the width, but then that also restricts the height.
    Reply 6 of this posting may give you some ideas.

  • Does JTextPane have document size restrictions?

    I am running into a problem while using a JTextPane to display documents. I have written a simple test class as can be seen below. The largest file I can read in using jdk1.4_2 is 1.6MB. If I use jdk1.4_0, the size is reduced to 0.6MB. I have search in the problem database and could find nothing. Has anyone else seen similar issues? Any ideas for work arounds?
    If I use a JTextArea, I have not had this problem only with the JTextPane. I do need to have the ability to display HTML, that is why I have stuck with the JTextPane.
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    public class ReadTest extends JFrame {
        JTextPane editor;
        JScrollPane scrollPane;
        public ReadTest() {
             super("Test Editor");
             editor = new JTextPane();
             if(loadData()) {
                 createUI();
        public void createUI() {
             Container contentPane = getContentPane();
             scrollPane = new JScrollPane( editor,
                 JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,    
                 JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
             scrollPane.setPreferredSize( new Dimension( 600, 800 ) );
             scrollPane.getViewport().setScrollMode( JViewport.SIMPLE_SCROLL_MODE );
             contentPane.add( scrollPane );
             setSize( 625, 800 );
             setLocation( 300, 200 );
             show();
        public boolean loadData() {
            boolean result = true;
            FileInputStream test = null;
            try {
                File outFile = new File("C:\\temp" + System.getProperty( "file.separator" ) + "test.out");
                test = new FileInputStream(outFile);
            catch(FileNotFoundException e){
                result = false;
            if( test != null ){
                try{
                    editor.read(test, null);
                catch(IOException e){
                    result = false;
            return( result);
        public static void main(String[] args) {
            ReadTest myEditor = new ReadTest();
    }

    Hi Joe,
    It seems that your print drivers are limiting your options. Using a different print driver may help.
    I've included a link to a post here that might help.
    "Although I work for HP, I'm speaking for myself and not on behalf of HP"
    "Say "Thanks" by clicking the Kudos Star in the post that helped you.
    --Please mark the post that solves your problem as "Accepted Solution"

  • Horizontal scrollbars with a JTextPane component

    Hi all
    I use a JTextPane which is, in turn embedded in a JScrollPane. In some cases, text appended might be longer than the current width of the window. In this case, I would like the JTextPane to show the scrollbars (Policy set to "show when needed") instead of wrapping the text line. How can this be done?
    Regards,
    Michael
    PS: The text is represented by a DefaultStyledDocument.

    Hi there
    I don't think that's the problem. The JTextPane is already to the ScrollPane and the ScrollPane is in turn added to aJPanel. That works so far.
    I think the problem (probably) has to do with the JTextPane (guess). In a similar case, i use a JTextArea and here it works ok (i.e. provides the scrollbars and not wrap the text).
    To illustrate, here's the code that does that:
    ---<snip>---
    JInternalFrame dashboardOutputFrame = new JInternalFrame();
    DefaultStyledDocument dashboardOutputDocument = new DefaultStyledDocument();
    JTextPane dashboardOutputEditor = new JTextPane(dashboardOutputDocument);
    JScrollPane sp = new JScrollPane();
    BorderLayout l = new BorderLayout();
    dashboardOutputFrame.setTitle("Standard Output Window");
    dashboardOutputFrame.setSize(600, 300);
    dashboardOutputFrame.setLocation(20, 20);
    dashboardOutputFrame.setClosable(false);
    dashboardOutputFrame.setFrameIcon(personIcon16);
    dashboardOutputFrame.setIconifiable(true);
    dashboardOutputFrame.setMaximizable(true);
    dashboardOutputFrame.setResizable(true);
    dashboardOutputFrame.getContentPane().setLayout(l);
    sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    sp.setViewportView(dashboardOutputEditor);
    dashboardOutputFrame.getContentPane().add(sp, BorderLayout.CENTER);Cheers,
    M.

Maybe you are looking for

  • CE Bank Statement Auto-Reconciliation failure

    Hey guys, We have this problem about auto-recon not finding a match even if the bank statement line has an equivalent available transaction for reconciliation. I am guessing it doesn't refer to the amount as the matching criteria. I checked Oracle su

  • More Memory Needed???

    I have recently upgraded to Leopard on my iMac G5 with 512 MB Ram. Since the upgrade my Mac has been running slowly. If I try to run several programs, it sometimes takes a very long time for a program to come up. Also, often the fans will run very lo

  • Mime Attachments in Hotmail

    When I recieve mime attachments in Hotmail, the slide-show viewer shows the pictures, but the pictures won't load in the body of the email. Microsoft's Help Center tells me to update Internet Explorer to fix the problem. Hello?? IE hasn't been suppor

  • Queues and Exceptions

    Ok, I have a program that involves queues. Now, when the program checks if a queues is empty, if it is, it is supposed to handle an error. My prof uses "Underflow" , but I keep getting errors that it is undefined. I looked in the API and couldn't fin

  • Running slooooowly

    I have around 11400 songs on my iPod taking up around 60Gb. When I select artist or album it takes around 15 seconds for it to generate the list. (it's a long 15 seconds). For this many songs is it normal for it to respond pretty slowly?