Getting Visible text - JTextPane in a JScrollPane

I have a JTextPane wrapped in a JScrollPane. I want to be able to get the text that is visible at any given time. I want JUST the text that is visible, not the entire text of the document.
The method to use is obviously getText(int offset, int length), which is from JTextComponent.
I am wondering how I can retrieve the given offset (ie. the position of the very first visible character) and length (ie. the ending position of the last visible character minus the position of the starting character) from either the JScrollPane or the JTextPane.
I believe that this might be a rather complex problem as I'm qutie certain I am going to have to manually compute a few things by using several different views.
Any help anyone could offer would be most appreciated.

Hi camickr
I got the JScrollPane now thanks.
Now I'm still confused on how to solve the original problem.
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
public class TestJTextPane extends JTextPane implements ComponentListener{
      public static void main (String args[]){
           JFrame mainFrame = new JFrame();
           mainFrame.setSize(500,300);
           mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
           mainFrame.getContentPane().add(new JScrollPane(new TestJTextPane()));
           mainFrame.setVisible(true);
      public TestJTextPane(){
            this.addComponentListener(this);
      private void viewVisibleText(){
           int offSet = 0;
           int length = 0;
           try{
                JScrollPane scrollPane = (JScrollPane) this.getParent().getParent();
                System.out.println(scrollPane.getViewport().getVisibleRect());
                System.out.println(this.viewToModel(scrollPane.getViewport().getVisibleRect().getLocation()));
           catch (Exception e){
                e.printStackTrace();
     public void componentResized(ComponentEvent arg0) {
          viewVisibleText();
     public void componentMoved(ComponentEvent arg0) {
          viewVisibleText();
     public void componentShown(ComponentEvent arg0) {
     public void componentHidden(ComponentEvent arg0) {
          // TODO Auto-generated method stub
}If you run this, you will see that the Rectangle for the getVisibleRect() does not changed, and the call to viewToModel will always return 0.
Can you please point out where I'm going wrong.
Thanks for the help

Similar Messages

  • How to get the visible text in JTextField?

    I want to compare the space occupied by English and Japanese characters in the visible area of JTextFiled. I tried the same by taking the length of the characters occupied by the same text in both the language . But this did not work . I even tried the method getVisibleRect().
    Can please some one suggest a method or procedure by whcih i can get the length of the visible text in the JTextField
    Thanks
    Inder

    Point point = new Point(brm.getExtent(),0) ,it wont workWell, theoretically, the "Y" value shouldn't matter, but I guess when you display a line the text, the first couple of "Y" pixels are the spacing between lines and will presumably return the position of the character on the previous line (when using JTextArea, JTextPane). But since JTextField doesn't have a previous line I guess its returning 0. Change the "Y" value to 2 (1 doesn't work either):
    import java.awt.*;
    import javax.swing.*;
    public class Test
         public static void main(String[] args)
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              JTextField textField = new JTextField("Some text");
              frame.getContentPane().add(textField);
              frame.pack();
              frame.setLocationRelativeTo( null );
              frame.setVisible(true);
              for (int i = 0; i < textField.getSize().width; i += 5)
                   Point p = new Point(i, 2);
                   System.out.print(p + " : ");
                   System.out.println( textField.viewToModel(p) );
    }

  • How to get the text in a label which is imbeded in a JTextPane

    I have created a JTextPane that has 5 JLabels inserted in the text. I have attempted to get the text with the following code snippet.
    Component[] lbl = new Componennt[DisplayLetterPane.getComponentCount()];
    //         JTextPane DisplayLetterPane; is defined previously
             lbl = DisplayLetterPane.getComponents();
             int componentIndex = 0;
             String lblText = new String(((JLabel)lbl[componentIndex]).getText());I have run a dump of the sytledDocument of the JTextPane and I see the JLabel listed as a component.
    When this snippet is executed I get the following:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: javax.swing.text.ComponentView$Invalidator
    When I check the character where the component for the JLabel is located in the styled document it does not find an instanceof JLabel.
    How can I get the text from the labels.
    Thank you in advance!

    JTextPane jtp = new JTextPane();
              for (int i = 0; i <5; i++) {
                   jtp.add(new JLabel("labelText"+i));
              Component[] lbl = new Component[jtp.getComponentCount()];
    //      JTextPane DisplayLetterPane; is defined previously
          lbl = jtp.getComponents();
          int componentIndex = 0;
          for (int i = 0; i < lbl.length; i++) {
               System.out.println(((JLabel)lbl).getText());
    When I do like the above, it just works fine. Can u share a little bit more of your code?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • JTextPane inside a JScrollPane: any way to display a certain section?

    I have a GUI with a JTextPane inside a JScrollPane.
    The text of the JTextPane is the contents of a text file, so it typically has many lines.
    I want the JScrollPane (whose preferred size has already been previously set to display 11 rows of text) to always show one target line as the middle row, and the 5 rows before and after it as the remaining 10 rows.
    In other words, I want to show a certain line and its surrounding context.
    Do you guys know how to achieve this? I have already tried calling
    JTextPane.setCaretPositionbut this is inadequate because it merely guarantees that the line with the caret is visible--but it does not guarantee to center the caret line in the middle of the JScrollPane.
    I also tried calling
    textPane.scrollRectToVisible( textPane.modelToView(caretPos) );where textPane is my JTextPane, but this failed completely (seems to always display the final lines of the file).
    Anyone have any suggestions?

    Daryl: thanks for your response.
    My original code looked like this:
    int caretPos = 0;
    for (int i = 0; i <= index; i++) {
         caretPos += lines.length();
    textPane.setCaretPosition(caretPos);
    With *just* the above, you get the behavior that I originally described, namely, the line in question (which is lines[index]) always gets displayed, but it is not necessarily in the middle of the JScrollPane.
    I tried commenting out the line above which calls setCaretPosition, and used essentially your code instead:Rectangle caretRectangle = textPane.modelToView(caretPos);
    Rectangle viewRectangle = new Rectangle(
         0, caretRectangle.y - (scrollPane.getHeight() - caretRectangle.height) / 2,
         scrollPane.getWidth(), scrollPane.getHeight()
    textPane.scrollRectToVisible(viewRectangle);This fails too: the JScrollPane now always shows the bottom of the JTextPane.
    What does work is to use *both* techniques, namely, call setCaretPosition as well as scrollRectToVisible:     // set the caret to the line in question (i.e. at index); this merely guarantees that this line is visible, but not necessarily centered
    int caretPos = 0;
    for (int i = 0; i <= index; i++) {
         caretPos += lines[i].length();
    textPane.setCaretPosition(caretPos);
         // and IN ADDITION cause scrollPane's viewport to be centered around the line
    Rectangle caretRectangle = textPane.modelToView(caretPos);
    Rectangle viewRectangle = new Rectangle(
         0, caretRectangle.y - (scrollPane.getHeight() - caretRectangle.height) / 2,
         scrollPane.getWidth(), scrollPane.getHeight()
    textPane.scrollRectToVisible(viewRectangle);The interesting question is why do you need to do both steps?
    I think that I know the reason, but I would love to see someone confirm or deny this.  What follows is my speculation.
    The above code is inside a method that is call by a run method of the class in question which is always executed by the event dispatch thread (EDT), so it is not an illegal thread use case.  However, in the method that has the code above, I am clearing all existing text of the JTextPane and then repopulating it (with that String[] lines used above, which came from parsing a file).
    Now, in  [this posting|http://forums.sun.com/thread.jspa?messageID=10289999#10289999], camickr claimed:
    "When text is inserted into a Document, behind the scenes a call to setCaretPosition() is made to position the caret after the newly inserted text. However inserting text into a document is a complex procedure since Elements need to be created as the text inserted into the Document is parsed. So the call to the setCaretPosition() method is placed in a SwingUtilities.invokeLater(), which means tha code gets added to the end of the GUI EDT to be executed once the Document is in a complete state. So basically what is happening is that your call to set the view position does execute, but then is gets overridden by the setCaretPosition() method call."
    If the above claim is true, then all the calls in that method to add the file's text result in implicit calls to setCaretPosition which will be executed AFTER the method above ends (i.e. asynchronously, later on by the event dispatch thread).  Hence, I need to do an explicit setCaretPosition call of my own to override these implicit calls.
    Now, I am not sure that I totally buy this explanation.  I would like to see more proof of camickr's claims for one: I did a quick code review of some of the classes involved, and do not see where calling AbstractDocument.insertString generates an implicit call to setCaretPosition on the EDT.  To be sure, the code is complex, and I do not know where exactly to look, and maybe this is done by some listener or something, who knows.  Furthermore, my explicit call to setCaretPosition is done synchronously on the EDT (recall: that method above in my class is called by its run which is executed by the EDT).  So, my explicit call to setCaretPosition should occur in time before all of those delayed implicit calls, and thus should actually be overridden by them, no?
    I would love to hear from someone who really knows Swing...                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • ExtendScript: Get all text from a document

    Hi all.
    I have the following task: I need to translate a document into another language using ExtendScript. So, as "input" I have a document with a text/graphics/tables/etc. in Language_1 and a "somehow-separated file", which will contain data about translation into the Language_2. E.g.:
    Some_text_in_language_1     Some_text_in_language_2
    Some_other_text_in_language_1     Some_other_text_in_language_2
    To get the source text from the document, I've tried to use this:
    var pgf = doc.MainFlowInDoc.FirstTextFrameInFlow.FirstPgf;
    while(pgf.ObjectValid()){
         var test = pgf.GetText(Constants.FTI_String);
         var text, str;
         text = "";
         for (var i=0; i < test.len ; i +=1)
              var str=test[i] .sdata.replace(/^\s+|\s+$/g, '') ; 
              text = text + str;
              PrintTextItem (test[i]);
         pgf = pgf.NextPgfInFlow;
    But with this, I can only access the regular text in the document (e.g. the text in tables remains untougched). Is there any way I can the all textual data from specified document? Or maybe, the full list of controls, which can contain it, to iterate throught them and extract it one-by-one? Or maybe there's a better way to solve this problem?
    Thanks in advance! Any advice would be greatly appreciated.

    There is another way to loop through ALL paragraphs in a document, regardless whether they are in a table or in the main text flow. You can use the FirstPgfInDoc property of the document and loop through all Pgf objects using the NextPgfInDoc property of the Pgf until you reach an invalid object. Note that this also includes all paragraphs in the master and reference pages, so it might be useful to check where the Pgf is located (on a body page or not). There is a script on this forum that does that - I believe it was created and posted by Rick Quatro.
    Working your way through the main text flow does not guarantee that you have all the visible text in the doc. There may be multiple flows and there may also be text frames that are placed inside anchored frames. Those text frames are not contained directly in the main flow of the document.
    Good luck with your scripting
    Jang

  • Printing Only visible text

    Hi,
    I am trying to print an editable PDF from Adobe reader. The issue is that only the text visible in the edit boxes are printing. I have several paragraphs of written text in the editable boxes, but when it only prints the few sentences that are visible. How do I get the ALL my text to print, instead of just the visible text?
    Any help would be greatly appreciated!!!
    Thanks!
    Sarah

    Not really. You can copy the text to another field (for example, on a blank
    page) when the file is printed, but that would require using a custom-made
    script.

  • How can i put text/chars inside a text area inside a JScrollPane?

    ive tried:
    receipt.setText("blah blah") // but it does not work. all i get is still a blank text area inside a JScrollPane
    JTextArea receipt;
    JScrollPane sp;
    receipt = new JTextArea();
    sp = new JScrollPane(receipt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);

    mstrnew = new JButton //this should clear receipt
    if(evnt.getSource()==mstrnew)
                  order.setText("");
                  price.setText("");
                  total.setText("0.0");
                  cash.setText("");
                  change.setText("");
                  mstrtotal = 0;
                  JOptionPane.showMessageDialog(null,"              Starting New Transaction...","",JOptionPane.PLAIN_MESSAGE);    receipt.setText("");}
    else if(evnt.getSource()==vm1)
                  generate("           2pc. Chicken Strips Meal\n");
                  order.setText("2pc. Chicken Strips");
                  price.setText("61.0");
                  mstrtotal = Double.parseDouble(price.getText()) + Double.parseDouble(total.getText());
                  total.setText(String.valueOf(mstrtotal));
    // scrollpane part
                 receipt = new JTextArea();
                 receipt.setEditable(true);
                 //receipt.setLineWrap(true);
             up = "\n          YUM! Brands Corporation, Kentucky Fried Chicken ?\n                       KFC LaSalle Branch, Taft Ave., Manila\n\n           88788   TIN-209-670-390-002   REG VAT   POS#113\n           SN:41-HK170 All prices were subjected of 12% VAT.";
             mid = "\n\n";
             down = "\n";
             complete = up+mid+down;
             receipt.setText(complete);
             sp = new JScrollPane(receipt,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    public void generate(String z)
             mid += z;
             complete = up+mid+down;
        }Message was edited by:
    ice3d

  • Number of visible text fields

    Hi all,
    Trying to upload document numbers from Excel into SAP via transaction F-03 using SAP GUI Scripting.
    My approach is to enter values one by one and press Enter when the last visible text field is reached. Then enter another batch of values, press Enter and so on..
    The problem is that I do not know how to get that event when the last visible field is reached.
    I know the solution but for tables when you can count a number of visible rows (.visibleRowCount).
    Thanks in advance.

    Hi Dmitry,
    in this case, I would proceed as follows:
    1. before the position command the system error handling switch off with
    on error resume next
    2. behind the position command the test of error number with
    if err.number < 0 or err.number > 0
    For example:
    on error resume next
    err.clear
    'position command from existing script
    if err.number > 0 or err.number < 0  then
    'processing . . .
    end if
    on error goto 0
    Declaration on the solution: In a non-relevant line will it not work. This one can evaluate it.
    Regards,
    ScriptMan
    Edited by: ScriptMan on Apr 19, 2010 7:36 PM

  • HT201401 My iphone 4 is not ringing, or notifying me when i get a text message or email

    My iphone4 is not ringing, or notifying me when I get a text message or email. It does however vibrate, the alarm works, and I am able to play music. The button to swith vibrate on and off, seems to not be working. Also, the sound buttons. The up button does not work, but the down button does. I have restarted, restored, and changed the ring. Nothing seems to be working. Has anyone had this problem? If so, how did you go about getting it fixed?

    Did you accidentally move the slider button above the volume control to the "off" position (orange dot visible)? My husband used to do that all the time.

  • How do I get more text options in photoshop??

    How do I get more text options in Photoshop?  I have the basic package, but I would like more script options.
    Thank you,
       Maureen

    I don't suppose you have a full CC subscription?  It comes with a feature called Typekit which I love. Along with an ever increasing range of top quality fonts, it has the best font manager I have used, and excellent search facility.
    The web is full of additional font sites like dafont
    http://www.dafont.com/
    Otherweise, Google is your friend
    If you want Text Effects then Google will help you out there as well

  • I made my own apple id because my family was getting my texts from other people. I want to add my device to my dads find my iphone app on his icloud but can't figure out how, without having to log in to his apple id on my phone. how do i add my device?

    I made my own Apple ID because when I was logged into my dad's my family was receiving my texts from other people. I want to add my device to my dad's "find my iphone" app but without signing into his Apple ID on my phone because that was causing them to get my texts. I was told by Apple I could add my device to his by signing into icloud.com but there is no option that I can find to add my device. And I don't want to log back in to his.. Any ideas???

    Also when I apply the safety copy it only imports the app the phones have had in common, so none of the apps that only the iPhone 4 had doesn't come in, only the ones I and the iPhone 4 has had in common. So you say the only way I can use the Apple ID to download on the old iPhone 4 is if I delete the apps that are in the phone and then download them again? How will that change the ID to download/update from. Won't it still have mine to update/download from?

  • How do I get a text file from Photoshop  to work in the main sequence in pp?

    How do I get a text file to work properly in the master sequence. I moved it from Photoshop, which I learned to do from a tutorial, but when I move the animated text sequence to the master, it either isnt running, or it is scaled way too big. How do I get it to run in the main sequence?

    "Wont Work Here" !  Does not mean much.
    Are you having an audio or a video issue? 
    Looks like no video clip on the video layer above that section of audio.
    I am teaching myself this stuff completely on the fly
    I suggest you do the Basic Tutorials ( Adobe TV for example) in both Premiere Pro and PhotoShop.
    You need to be competent in the basics and fundamentals of these apps and that will also help you describe and discuss the issues.   Check the 'Products on this site....
    Adobe TV

  • How do I get the text to flow throughout more then one page.

    Hello,
    I am currently using LiveCycke Designer to create a scholarship for my company. I created fields for the form and I would like to insert a text to describe the scholarship. When I insert the text, it doesn't flow onto the next page. I've tried creating a subform and clicking "flowed" and "allow page breaks within content". I also clicked auto-fit for the height, but it just makes a line. For the text box, I've clicked "Expand to fit on the height". It is also a dynamic XML Form. Is there anything else I should be doing?
    I could always send the file to someone to see if they can figure it out.
    Thank you,
    Natalie

    Thank you so much !
    but the link doesn't seem to work. It says that the URL is not in the correct format for an Acrobat.com document link.
    Natalie
    Date: Wed, 12 May 2010 07:53:12 -0600
    From: [email protected]
    To: [email protected]
    Subject: How do I get the text to flow throughout more then one page.
    Here is the corrected form..Even you you set the Subform type to "Flowed" to the subform where the Text box resides, you did not set the Page1 to Flowed (which is the key)..But when I make the Page1 type to "Flowed", all your fields above the Scholrship text boxes' Subform will go one below another.. To fix this, first I have select all the fields and wrap them into a subform and then set the Page1 to Flowed..
    https://acrobat.com/#d=XQ1yfV8fCk85M7sRLD*-gg
    Thanks
    Srini
    >

  • How can I get the "text" field from the actionEvent.getSource() ?

    I have some sample code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.ArrayList;
    public class JFrameTester{
         public static void main( String[] args ) {
              JFrame f = new JFrame("JFrame");
              f.setSize( 500, 500 );
              ArrayList < JButton > buttonsArr = new ArrayList < JButton > ();
              buttonsArr.add( new JButton( "first" ) );
              buttonsArr.add( new JButton( "second" ) );
              buttonsArr.add( new JButton( "third" ) );
              MyListener myListener = new MyListener();
              ( (JButton) buttonsArr.get( 0 ) ).addActionListener( myListener );
              ( (JButton) buttonsArr.get( 1 ) ).addActionListener( myListener );
              ( (JButton) buttonsArr.get( 2 ) ).addActionListener( myListener );
              JPanel panel = new JPanel();
              panel.add( buttonsArr.get( 0 ) );
              panel.add( buttonsArr.get( 1 ) );
              panel.add( buttonsArr.get( 2 ) );
              f.getContentPane().add( BorderLayout.CENTER, panel );
              f.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              f.setVisible( true );
         public static class MyListener  implements ActionListener{
              public MyListener() {}
              public void actionPerformed( ActionEvent e ) {
                   System.out.println( "hi!! " + e.getSource() );
                   // I need to know a title of the button (which was clicked)...
    }The output of the code is something like this:
    hi! javax.swing.JButton[,140,5,60x25,alignmentX=0.0,alignmentY=0.5,
    border=javax.swing.plaf.BorderUIResource$CompoundBorderUIResource@1ebcda2d,
    flags=296,maximumSize=,minimumSize=,preferredSize=,defaultIcon=,disabledIcon=,
    disabledSelectedIcon=,margin=javax.swing.plaf.InsetsUIResource[top=2,left=14,bottom=2,
    right=14],paintBorder=true,paintFocus=true,pressedIcon=,rolloverEnabled=true,
    rolloverIcon=,rolloverSelectedIcon=,selectedIcon=,text=first,defaultCapable=true]
    I need this: "first" (from this part: "text=first" of the output above).
    Does anyone know how can I get the "text" field from the e.getSource() ?

    System.out.println( "hi!! " + ( (JButton) e.getSource() ).getText() );I think the problem is solved..If your need is to know the text of the button, yes.
    In a real-world application, no.
    In a RW application, a typical need is merely to know the "logical role" of the button (i.e., the button that validates the form, regardless of whether its text is "OK" or "Save", "Go",...). Text tends to vary much more than the structure of the UI over time.
    In this case you can get the source's name (+getName()+), which will be the name that you've set to the button at UI construction time. Or you can compare the source for equality with either button ( +if evt.getSource()==okButton) {...}+ ).
    All in all, I think the best solution is: don't use the same ActionListener for more than one action (+i.e.+ don't add the same ActionListener to all your buttons, which leads to a big if-then-else series in your actionPerformed() ).
    Eventually, if you're listening to a single button's actions, whose text change over time (e.g. "pause"/"resume" in a VCR bar), I still think it's a bad idea to rely on the text of the button - instead, this text corresponds to a logical state (resp. playing/paused), it is more maintainable to base your logic on the state - which is more resilient to the evolutions of the UI (e.g. if you happen to use 2 toggle buttons instead of one single play/pause button).

  • Hi, Im having trouble with my Iphones sounds, it wont let me listen to music, watch videos, notify me if i get a text, basically everything that makes a sound is no longer working. The volume level you get when you play music isnt there, HELP?!

    Hi, basically i have no sound at all on my Iphone, it doent notify me when i get a text, when someone rings, when i play music or watch videos, the volume slider that is usually present while watching videos or listening to music is no longer there at all, ive turned my phone on and off a couple of times now ive put headphones in and out to see if i had a sticky jack but still no luck Someone help??

    And to clarify, these are all iTunes movie and music downloads, so there should not be a compatability issue. And no, the iPod did not come damaged from Apple, it was a hand-me-down from a friend who busted the internal speaker. But it's never done anything like this before. It just had crappy sound. And yes, the timing of the movies and music having issues is the same as the speaker dying. And no, this has NOTHING To do with music videos. I don't have any on any of our devices.

Maybe you are looking for