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

Similar Messages

  • Any way to display a message when Flash is not found on the iPad?

    Apple is obviously rejecting Flash to protect it's 'App' revenue.  I've  been on Android phones that run Flash and display all my content  perfectly smooth.  It can be quite frustrating how they are trying to  bury it when I still have yet to see HTML5 replicate the type of  interactive content Flash is capable of producing. 
    Is there any way to display a message on the iPad when the Flash player is not found?
    I'd like it to says something along the lines of:
    "Unfortunately the Apple iPad does not support the Flash player  because their business interests do not want it taking away from their  App revenue.
    Did you know that the Dell Streak, HTC Flyer, Blackberry Playbook,  Motorola Xoom, Samsung Galaxy Tab, Toshiba Thrive, and HP Touchpad all  support the Flash player?"
    My HTML code looks something like this...
    <html>
    <head>
    <title>My Page</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body bgcolor="#ECECEC" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
    <body onresize="setFlashSize()">
    <div id="flashid" style="width:100%; height:100%;">
    <script type="text/javascript" language="JavaScript">
    function setFlashSize(){
    var viewportheight = document.body.clientHeight;
    var viewportwidth = document.body.clientWidth;
    var mydiv = document.getElementById("flashid");
    var styleheight = parseInt(mydiv.style.height);
    var stylewidth = parseInt(mydiv.style.width);
    if (viewportwidth<880){
    document.getElementById("flashid").style.width = 880+"px"; }
    else {
    document.getElementById("flashid").style.width = 100+"%";}
    if (viewportheight<760){
    document.getElementById("flashid").style.height = 760+"px"; }
    else {
    document.getElementById("flashid").style.height = 100+"%";}
    setFlashSize();
    document.write('<object data="index1.swf" width="100%" height="100%" type="application/x-shockwave-flash">');
    document.write('<param name="movie" value="index1.swf" />');                      
    document.write('<param name="allowScriptAccess" value="always" />');       
    document.write('</object>');
    </script>
    <noscript>Javascript must be enabled to view Flash movie</noscript>
    </div>
    </body>
    </html>

    Use swfobject for Flash detection and you can provide all kinds of alternate content... simple text, images, links, .js slideshow, a mov or mp4 video just for the iPhone... ANYTHING this is regular HTML. Your imagination is the only limit.
    And YES, HTML5 is a far cry from replicating Flash... so give them the best of both worlds.
    http://code.google.com/p/swfobject/
    Review this article which deals with Flash and SEO for more ideas:
    If you think that Flash is somehow bad for SEO, it's time to dispell that MYTH!
    If fact, in some circumstances I'll use Flash INSTEAD of just HTML because then I'll have better SEO than with just HTML alone.
    http://www.worldbarefootcenter.com/
    The link to World Barefoot Center in the above post is just one example. View the source code and you see a couple paragraphs of text along with regular HTML links.... but what displays is the Flash version of the image and Flash links.
    The client provided the artwork for the page... and that's what they wanted to use a .jpg image. Well yes, that could be done in HTML but it would be virtually invisible to Google. So Instead I converted the image into a Flash .swf and used swfobject to display the Flash. swfobject allows you to create alternate content inside the <div> which also holds the Flash .swf, then when the page is loaded it detects if the browser has the Flash pluggin. If it does, it displays just the Flash content, if not, it displays the alternate content. Since almost everyone has the Flash pluggin, for most people the Flash version of the <div> will display.
    The alternate content for that <div> can be any regular HTML text, images, media player, links, etc., anything that you would use if you were not using the Flash. Now the best part is that the alternate content can be "over the top" as far as optimizing for SEO, since it will not be seen by most viewers.
    Here's another example of SEO with Flash.. again, the page is just a single image provided by the client:
    http://www.ksowetsuits.com/
    View the source code. The alt content is paragraph after paragraph of information about the site, including lists and links. If it was just the HTML, it might be kind of a boring Home page. But for SEO I can go "over the top" in promoting the site, since most viewers will never see that part... but it's all indexed by search engines. The end result is BETTER SEO using Flash than just HTML.
    On another Web site, a Flash video is displayed, the alt content is the complete text narration of the video. Now how many people would take the time to read that if they could just watch the video instead?? again, better SEO with Flash than without. In fact in one case we had first page search result from that video narration within 4 hours of posting the page.
    On still another site with a Flash video, the alt content is another video, but a .mov version, which will, in effect play Flash video on the iPhone (not possible you say??). Well since the iPhone does not have Flash pluggin, it simply displays the .mov version of the video, while everyione else sees the Flash version.
    So anyway, if Flash is a part of your Web development, you should look into using swfobject and alternate content.
    http://code.google.com/p/swfobject/
    Best wishes,
    Eye for Video
    www.cidigitalmedia.com
    Adninjastrator

  • Is there any way to display a file that contains text and pictures

    Hi all,
    I was wondering if java has any way to display a file that contains both text and pictures. I have tried using the RTFEditorKit and using an RTF file and it only diplays the text contained in the file and omits the pictures all together.
    code:
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.text.rtf.RTFEditorKit;
    public class Test
         JScrollPane scroll;
         JEditorPane edit=new JEditorPane();
         RTFEditorKit kit=new RTFEditorKit();
         public Test()
              final JFrame frame = new JFrame();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         edit.setEditorKit(kit);
         edit.setEditable(false);
         try
              kit.read(new FileReader(new File("Installation.rtf")),edit.getDocument(),0);
              catch(Exception e)
                   JOptionPane.showMessageDialog(null, e);
         frame.getContentPane().add(new JScrollPane(edit));
         Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
              frame.setBounds(0,0,screenSize.width, screenSize.height);
         frame.show();
         public static void main(String[] args)
    new Test();
    Please help!
    thanks in advance,
    Denise

    Not good as that usually means the project itself was corrupt.
    Any chance you sync'd to Creative Cloud? That's the only way I know of that backs up your PS Touch (PSDX) files.

  • Is there any way to display filenames or captions for photos?

    is there any way to display filenames or captions for photos?

    Thanks. There are so many it's very hard to see which one does what. Since I edit  on the MacBook Pro using Photoshop Elements, all I really need is a way of seeing the filenames, and secondarily re-arranging thumbnails on the iPad screen manually.

  • HT5554 20 days back myself ported network from vodafone in to airtel. But in my iphone5 its still showing vodafone in only. Done reset network setting, reztore but no use, can u ppl suggest any way to display carrier name correctly, ios i m using is ios7

    20 days back myself ported network from vodafone in to airtel. But in my iphone5 its still showing vodafone in only. Done reset network setting, reztore but no use, can u ppl suggest any way to display carrier name correctly, ios i m using is ios7

    Call your local Apple store. Not sure how the phone system works in the UK, but here in the US there is a menu system that allows you to make an appointment. Or, you can go online to www.apple.com/retail, or you can use the Apple Store app and make an appointment there after selecting the particular store.

  • Is there any way to display JTree without using applet

    Hi,
    is there any way to display JTree without using applet . Can we display the JTree in a JSP page.
    With Regards,
    Sheema.

    Not a JTree, per se. But there are Javascript solutions out there and there are JSP tag library solutions which use a JTree on the server side to hold and maintain the data and expanded nodes.
    This is one that I've used before, it's pretty good:
    http://www.jenkov.dk/treetag/introduction.tmpl

  • Any way to display dorpdown menu over quick time player

    hi all,
    Is there Any way to display dorpdown menu over quick time
    player in Dynamic HTML page like the flash parameters wmode
    transparent....The menu and quick time is different Td's
    Thanks

    Not that I know of.
    Murray --- ICQ 71997575
    Adobe Community Expert
    (If you *MUST* email me, don't LAUGH when you do so!)
    ==================
    http://www.projectseven.com/go
    - DW FAQs, Tutorials & Resources
    http://www.dwfaq.com - DW FAQs,
    Tutorials & Resources
    ==================
    "jibysk" <[email protected]> wrote in
    message
    news:ff9rjk$i6l$[email protected]..
    > hi all,
    >
    > Is there Any way to display dorpdown menu over quick
    time player in
    > Dynamic HTML page like the flash parameters wmode
    transparent....The menu
    > and quick time is different Td's
    >
    > Thanks

  • Project Web App (PWA)/Sharepoint 2013: is there any way to display two different views of the Project Center PWA web part to the same user in a site collection?

    i want some of my users to see all the projects in the Project Center at my top-level site, and those same users to see only the projects they own at a subsite level in Project Center. that way they could see an 'all project' view on the homepage and only
    their projects on their dashboard pages (which also have an instance of Project Center web part on them). i have searched and searched but cannot find a solution to this. is there any way to acheive this functionality? thanks in advance for your assistance!

    I have tried this in the past, but was not successful, as far as I can recall. Once you access the project center webpart in one page, the view will be retained regardless where you see it again. (until you apply a different view or clear your browser cache). 
    May be an easier solution is to display a 'report' on the home page with ALL projects (much easier to do), and use the Project Center webpart for the My projects view as it is easier to achieve via Project Server Security, than a report.
    Cheers,
    Prasanna Adavi, Project MVP
    Blog:
      Podcast:
       Twitter:   
    LinkedIn:
      

  • Any way to display row-level errors in AdvancedTable from ProcessRequest?

    I have a page which displays data in an Advanced Table. Users are also able to edit the data on each row, and then save. Upon saving, it will validate the data, and display row-level errors (via either OARowValException or OAAttrValException). That's all working fine.
    The issue I have, is that sometimes data can become invalid from outside of this particular screen. So when a user opens the screen, some of the data displayed is already invalid. If the user saves, without changing anything, they'll see the errors. I want to show the errors immediately, without them having to save on every range of records. So I basically want to re-validate everything when it is first displayed, so from ProcessRequest. Is there any way to actually do that? I've tried several ways, but nothing seems to work.

    Hi,
    I havent used it but u can try with the below logic
    Write ur logic in AM...
    Import oracle.apps.fnd.framework.OAAttrValException
    Import oracle.apps.fnd.framework.OARowValException
    //Iterate through all the rows.
    if(attr1!=attr2)
       throw new OARowValException (
            getEntityDef().getFullName(), // entity full definition name
            getPrimaryKey(),              // entity object primary key
            "FND",                        // message application short name
            "ATTR_EXCEPTION");            // message name Regards,
    Gyan

  • Any Way to display HTML pages on Applet

    Hi All,
    Is there any way to show web pages on Applet?
    Is it possible ?

    I am not aware of a simple way to display HTML in an applet. However, I have used the JEditorPane to display HTML documents. Handling links, etc. with this component requires some effort. Also requires Swing.
    Have you considered using the applet to display a page on the browser. (i.e. getAppletContext().showDocument(URL, [frame name]))? Just an idea.
    Good luck.

  • I would like to know if there is any way to display an animated gif on an ipad

    I would like to know, is there any way or app that allows you to display an animated gif on an iphone or ipad ? for example, just like when you go into your camera roll and it displays a picture, be able to display a moving picture ( animated gif) 

    You can use GifViewer Pro https://itunes.apple.com/us/app/gifviewer-pro-animated-gif/id629527680?mt=8
     Cheers, Tom

  • Is there any way to display document page numbers and section page numbers at the same time?

    Hi, I have different sections within my document starting the page numbering at 1. Besides the section page numbers I would also like to display the actual document page numbers in the header (eg. you are on page 10 of the document and page 4 of the section). Is there any way to do that? Thanks

    You can maybe use the Find/Change
    Command+i
    See if that can work for you.
    But like Steve said it is good practice to use Paragraph Style whenever you have lots of Type, I just get lazy sometimes.. lol
    Thanks

  • Any way to display time code for source video?

    I don't see any way to get AE to display the embedded timecode of a source video.  AE does know this, as you can see it by looking at the metadata for a video.
    Does anybody know a plugin that does this, or has anyone written an expression already to do it, using the timecode window effect?
    :<)McFrisco

    As explained, AE does not expose this stuff. not to plug-ins, not to expressions. It's a long-standing issue, but can't be helped. In addition to using the TC effect, it may alos help to set the composition start time to the in-point time of the clip. Just a thought: Another way would be to take a detour via Premiere - apply the TC effect set to Media as source, import the Premiere stuff as DynamicLink items.
    Mylenium

  • Is there any way to display pictures in a report program...

    Is there a way to display some pictures say background or foreground pics in a report program ??
    Kindly help me in this.
    Thanks in advance,
    Krishna,
    9986023724

    Hi Krishna,
    Go througth the following document.
    <a href="http://help.sap.com/printdocu/core/Print46c/en/data/pdf/BCCIIMAGE/BCCIIMAGE.pdf">http://help.sap.com/printdocu/core/Print46c/en/data/pdf/BCCIIMAGE/BCCIIMAGE.pdf</a>
    Regards,
    sukhee

  • Is there any way to display a pdf inside of a swf file?

    Are there any software that will convert Word documents or pdf into swf files that ca be displayed inside of a Flash movie. Currently, I am using FlashPaper but the software is not supported anymore by Adobe. I am creating eLearning courses and having a pdf open inside of a course without opening multiple makes for a better learning experience. Any help will be greatly appreciated.

    http://cookbooks.adobe.com/post_PDF_2_SWF_Conversion-4701.html

Maybe you are looking for

  • SDO_AGGR_UNION crashes the session

    Hi! I am developing a PL/SQL overlay module to overlay two polygon layers (+ some additional logic). I also use SDO_AGGR_UNION function, which aggregates polygons previously created by SDO_INTERSECTION function. At this point session crashes with "en

  • Checking a tranaction in a role

    Dear All, Please help me how to check a transaction in a role? Thanks, Satya

  • Code Coloring - black background

    Has somebody Dreamweaver 8 configured to use black background in Code Editor? If so, please distribute the ColorCodings XML files somewhere. Thank you very much cs

  • GPIB erreur communication

    Bonjour, J'ai un problème d'exécution d'un vi bloqué sur un sous vi permettant l'initialisation d'un gaussmètre DG6 par une carte AT-GPIB/TNT branchée sur un port isa (avant de procéder à des mesures avec une sonde fixée sur une table 3 axes) Le sous

  • Why won't the new Nectar Search toolbar install into Firefox 25?

    I have used the Nectar Search toolbar with Firefox since it was introduced with no problems at all. Nectar have recently introduced a new Search toolbar to replace the previous version, and although I have re-installed it 3 times on my PC, (Windows X