Scrolling to a component

I have a JPanel that contained withn a JScrollPane (called flowchartPane). The JPane contains other JPanels that are arranged with a grid layout.
These JPanels contain graphics and when put together in various combinations make a flowchart.
The actual size of the JPane is larger than the viewport of the JScrollPane. So there are times when I want to scroll to a perticular component that is out of the bounds of the view port rectangle.
I am aware of the scrollRectToVisible method and have been utilising it in my method. However my method seems to be unreliable.
What the method attempts to do is, if a component (comp) has its left, right, top or bottom edge outside the bounds of the viewport scroll the viewport so the component is in view.
However this method is not reliable and does not allways do what is expected. Can anyone think of anyway I can improve it, see what I am doing wrong or help in the writing of a scroll to component method.
Kind regards
Andrew Scott.
   public void scrollToComponent( Component comp)
       int x = comp.getLocation().x;//get x location of  the component
       int y = comp.getLocation().y;//get the y location of the component
       int h = comp.getHeight();//get the height of the component;
       int w = comp.getWidth();//get the width of the component
      Rectangle vr = flowchartPane.getViewport().getViewRect();
      int newY = vr.x;
      int newX = vr.y;
      //if outside the bounds of the viewport
      if (  ((x+w) > (vr.x + vr.width)) |  (x < vr.x) |
      ((y+h) > (vr.y + vr.height)) | (y <  (vr.y))) 
        //Do not attempt to scroll to an posision zero or less on the X axis
        if (x-w > 0)
          newX = x;// - w ;
        else
          newX = x;
        //Do not attempt to sctoll to a position zero or less on the Y axis
        if (y - (h/2) > 0)
         newY = y;// - (h/2);
        else
          newY = y;
        flowchartPane.getViewport().scrollRectToVisible(new Rectangle(newX,newY,vr.width,vr.height));
      }//end if
   }//End Scroll to Component

Stanislav,
Close, but no cigar. I will say that is the best solution yet, but its far from perfect.
It does not want to scroll upwards or to the left. It will only scroll to the right or down.
Why is that??
From your ideas Stanislav I developed this method:
public void scrollToComponent( Component comp)
     Rectangle vr = flowchartPane.getViewport().getViewRect();
     int centerX=comp.getBounds().x + comp.getBounds().width/2;
     int centerY=comp.getBounds().y + comp.getBounds().height/2;
     int newX=centerX-vr.width/2;
     int newY=centerY-vr.height/2;
    flowchartPane.getViewport().scrollRectToVisible(new Rectangle(newX,newY,vr.width,vr.height));
}//end scroll to componentKind Regards.
Andrew.
Message was edited by:
scottie_uk

Similar Messages

  • Scrolling a custom Component (e.g. JPanel) with overridden paint(Graphic g)

    Hi.
    I&#8217;m creating an application for modelling advanced electrical systems in a house. Until now I have focused on the custom canvas using Java2D to draw my model. I can move the model components around, draw lines between them, and so on.
    But now I want to implement a JScrollPane to be able to scroll a large model. I&#8217;m currently using a custom JPanel with a complete override of the paint(Graphic g) method.
    Screen-shot of what I want to scroll:
    http://pchome.grm.hia.no/~aalbre99/ScreenShot.png
    Just adding my custom JPanel to a JScrollPane will obviously not work, since the paint(Graphic g) method for the JPanel would not be used any more, since the JScrollPane now has to analyze which components inside the container (JPanel) to paint.
    So my question is therefore: How do you scroll a custom Component (e.g. JPanel) where the paint(Graphic g) method is totally overridden.
    I believe the I have to paint on a JViewport instructing the JScrollPane my self, but how? Or is there another solution to the problem?
    Thanks in advance for any suggestions.
    Aleksander.

    I�m currently using a custom JPanel with a complete override of the paint(Graphic g) method. Althought this isn't your problem, you should be overriding the paintComponent(..) method, not the paint(..) method.
    But now I want to implement a JScrollPane to be able to scroll a large model.When you create a custom component to do custom painting then you are responsible for determining the preferredSize of the component. So, you need to override the getPreferredSize(...) method to return the preferredSize of your component. Then scrolling will happen automatically when the component is added to a scrollPane.

  • Horizontal Scroll in list component

    Hi,
    I'm using a list component which is populated from a textbox.  I've set the horizontal scroll policy to auto and also to on however  the scroll either doesn't appear (in the case of auto) or doesn't move (in the case of on).  Is there a setting which I need to modify to have the horizontal scroll working normally?
    Thanks

    I tried the invalidate method as follows but nothing happened:
    mylist.invalidate();
    Not sure if I explained myself well, I just want the horizontal scrollbar to appear and be able to move it when one or more items in the list are long and thus not all visible...thanks

  • Horizontal scroll for Tree component scrolls too far right

    I've enabled the horizontal scroll bar for the Tree component.
    But the scroll bar allows the user to scroll very far to the right into blank space.
    The maximum width of my components measures 124px, as calculated by measureWidthOfItems(0,0), and I've verified this by measuring pixels of a screen shot.
    I have tried adding an event to set the Tree.maxHorizontalScrollPosition, and I traced the value that I'm setting it to, and I also traced the value that it actually assumed after I set it. Both are 124px.
    So I can't understand the behavior. I can scroll something more like ~400px to the right with lots of blank space.
    Any ideas why?
    Thanks,
    David

    Hmm, I'm not sure why this works, but it works, so for completeness here's what I did (in case anyone else runs across this same thread):
    var measWidth:Number = myTree.measureWidthOfItems(0,0);
    filesTree.maxHorizontalScrollPosition = measWidth - myTree.width;
    I call the above code whenever the window is resized (in my app there are 2 places that can cause a resize of the window, I manually added calls to a function with the above code). There is also an example out there that resizes any time the window is resized, but if you do this then you really can't have liveDragging=true in a DividedBox (which I have) because the cost of resizing is very high and overtaxes the cpu when called many times consecutively. I just call it when the dragging is finished (that way I have live dragging enabled, but it only updates the scroll bars when the user stops dragging, which is visually acceptable).

  • Implementing a graph scrolling using JScrollPane component

    I would like to ask a question apropos using of JScrollPane component. A part of the default behaviour of this component is adjusting the component's state when the size of the client changes. But, I need to achieve an opposite effect - I need to adjust a size of my client when the size of JScrollPane (and its viewport) changes (for instance, when the user resizes the frame).
    I implement a graph component which will show the graph of a time function. This component should always show nnn seconds without connection to the size of the scroll pane's viewport. So, if the the scroll pane component is resized I need to adjust the size of my client in order to keep the displayed time period unchanged.
    Now the question: how may I check the size of the viewport when the size of the JScrollPane changes? And whether I can do it even if the JScrollPane component has no client?
    If you know any other method of achieving the same effect, plese let me know.
    Thanks.

    I still find getExten\tSize (and getViewRect) work for me. Here's another demo.
    In my component, there's a big oval thats bounded by my component and a smaller
    oval that should track with the viewport's bounds.
    import java.awt.*;
    import javax.swing.*;
    public class ViewportLemonJuice extends JPanel {
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawOval(0, 0, getWidth(), getHeight());
            Container parent = (Container) getParent();
            if (parent instanceof JViewport) {
                Rectangle rect = ((JViewport) parent).getViewRect();
                g.drawOval(rect.x, rect.y, rect.width, rect.height);
        public static void main(String[] args) {
            JComponent comp = new ViewportLemonJuice();
            comp.setPreferredSize(new Dimension(800,800));
            JScrollPane sp = new JScrollPane(comp);
            sp.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
            JFrame f = new JFrame("ViewportLemonJuice");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(sp);
            f.setSize(500,300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    }

  • How to Scroll the UIScrollBar component to the top?

    I'm using the UIScrollBar with a dynamic text field. If
    content gets scroll by the user, and then the text fiel dis update
    with new text, the new text remains "pre-scrolled". So, obviously,
    I want to set the scroll position to 0 every time I update the
    content in that field. But how do you do this?
    Is this something I do to the text field or to the
    UIScrollBar component?
    What is the method?
    Could somebody please give me an example?
    Thanks in advance...

    Silly me, I think I walked past this one several times
    thinking I had tried it.
    // To scroll the UIScrollBar to the top
    info_txt.scrollV = 1;
    My problem was that I was using the parantheses to pass the
    value, like this:
    // This doesn't work
    info_txt.scrollV(1);

  • Scrollpane scrolling manually to component

    Sorry that I am spamming another post that is not a question, but again I was fighting with Swing over something quite poorly documented and I must share my victory for future people that may struggle with the same (and use the forum search).
    Situation: a scrolling panel which manually handles scrollwheel scrolling. This will select one of the many JLabels holding icons in the panel, giving them a colored border when the active one.
    Requirement: when a label is selected that is out of view, the scrollpane should scroll to make that label visible.
    Now after examining the javadocs I realized that scrollRectToVisible() is the solution. This method requires a Rectangle of the position to scroll to, which you can easily get by calling getBounds() on the component (label in my example) that must be visible. So what I did was:
    - call scrollToVisibleRect() on the JScrollPane. This does not work, to my surprise
    - call scrollToVisibleRect() on the viewport. This works partially, the scrollpane scrolls down, but it will never scroll up
    - I also tried validate() here and there just to know for certain I am not crazy
    And finally after some more hair pulling and a google quest I stumbled upon the answer; you need to call scrollRectToVisible() on the component that you wrap the scrollpane around, not the scrollpane itself! So if you have something like:
    JPanel mypanel = new JPanel();
    JScrollPane sp = new JScrollPane(mypanel);You need to call mypanel.scrollRectToVisible() to make the scroll work!
    Source of the solution:
    http://www.esus.com/docs/GetQuestionPage.jsp?uid=989

    Its kind of dumb how they have when that broadcasts when
    scrolling is going on but not one directly when its stops.
    Thanks for your help.
    Heres what i used:
    _root.onMouseUp = function () {
    if (_xmouse>=0 && _xmouse<=555 &&
    _ymouse>537 && _ymouse<558) {
    trace('stop that');
    }

  • 10g Preview: Wheel scrolling in Business Component Browser

    This problem is found in the Business Component Browser, when a view object with many attributes is opened. The right-hand pane shows input fields for the view attributes.
    When I scroll with the mouse wheel in this pane, each "tick" of the wheel scrolls only a few pixels, rendering the wheel essentially useless for scrolling. Since other parts of the IDE behave more normally with regard to scrolling, I'm inclined to believe this is a problem with this panel in the Business Component Browser rather than a setting on my system.

    Not many -- the main requirement is that the number of attributes causes the pane to scroll vertically. This can be accomplished by sizing the main tester window small enough to make the pane scroll even with just a few attributes. Then the problem can be reproduced.

  • How to read data in  Page Control "Scroll Bar" in Component Buffer ?

    Folks,
    Hello. My Component has 2 pages: "JournalLine" and "JournalTotal". In the page "JournalLine", I insert page control "Scroll Bar" and then insert a record "JournalLine2" into the "Scroll Bar". Thus, the Component Structure is as follows:
    Scroll - Level0
    JournalLine
    JournalTotal
    Scroll - Level1 Primary Record JournalLine2
    The fields in "JournalLine" are Unit, ID, Date.
    The fields in "JournalTotal" are Unit, ID, Date, TotalDebit, TotalCredit.
    The fields in "JournalLine2" are Account, Amount.
    Since the record "JournalLine2" is inside of the page "JournalLine" and inside of page control "Scroll Bar", I click on "+" push button and add as many lines as I need and type in data into each line.
    My purpose is to add up all numbers in "Amount" field of "JournalLine2" and assign the total amount to "TotalDebit" or "TotalCredit" in "JournalTotal" page. My PeopleCode is as follows:
    Local RowSet &level0, &level1, &level2;
    Local Row     &total;
    Local Field     &field;
    &level0 = GetLevel0( );     /* get level0 Rowset */
    &total = &level0(2);     /* get row JournalTotal because it's on the 2nd position in level0 */
    &level1 = &level0.GetRow(1).GetRowSet(Scroll.JournalLine);     /* get level 1 RowSet for record JournalLine */
    &level2 = &level1.GetRow(2).GetRowSet(Scroll.JournalLine2); /* Assume this line gets all records in JournalLine2 */
    For &I = 1 to &level2.ActiveRowCount
         &field.Value = &field.Value + &level2.GetRow(2).JournalLine2.Amount.Value;
    End-for;
    &total.GetRecord(Record.JournalTotal).GetField(Field.TotalDebit).Value = &field.Value;
    &total.GetRecord(Record.JournalTotal).GetField(Field.TotalCredit).Value = &field.Value;
    I place the above PeopleCode in Record Field "Amount" FieldChange Event. Because all records and fields are in the component buffer, in Browser, after type in data into each line in the record "JournalLine2" in the page "JournalLine", then click on page tab "JournalTotal", the total amount should appear in the field "TotalDebit" or "TotalCredit". But nothing is in the field "TotalDebit" or "TotalCredit".
    The above PeopleCode is not working out. I place the above code in component record field "Amount" FieldChange Event as well and not working either. My questions are:
    First, Is it correct for the above PeopleCode to read all records in "JournalLine2" Scroll Bar in page "JournalLine" ?
    Second, Do we need to use some methods like ScrollSelect( ) to read those data in Scroll Bar ?
    Third, Do we need to use "ActiveRecordCount" instead of "ActiveRowCount" ?
    Thanks in advance !

    Folks,
    This question has been solved by myself. Thanks.

  • Setting up scrolling for a component which has g2d features...

    Hi, everyone, Im working on adding scrolling capablitlity to a component, as it currently exceeds the room I have given it. The problem is....
    1) My scrollbar is always hidden under my g2d images... If I click on top of where the scroll bar should be, like crazy it appears piece by piece.
    2) The scrollbar doesn't seem to be scrolling. BTW its on a regular panel (getContentPane()), is this a problem??
    Well....here's the relevant code (the code for the component)
    static class MyComponent extends JComponent {
    JScrollBar scroll;
    //~~~~~~~~~~~~~~Component Stuff~~~~~~~~~~~~~~~
              MyComponent() {
                        setBackground(Color.pink);
                        setBounds(0,0,500,500);
                        setBorder(BorderFactory.createLineBorder(Color.pink,10));
                        scroll = new JScrollBar(JScrollBar.VERTICAL,0,20,0,100);
                        scroll.setBounds(484,0,16,500);
                        scroll.setVisible(true);
                        add(scroll);
                        System.out.println(scroll.isEnabled() + "" + scroll.isVisible() + scroll.getBounds());
                        setVisible(true);
    Then in the main() function, I add it to the panel like so...
    MyComponent mc = new MyComponent();
    joe.getContentPane().add(mc);
    Thanks a lot,
    Mark

    Ok, I tried making the panel....but this has led to some strange(er) problems...
    Here's some info on my panels
    JPanel something....is the panel holding buttons, and under a flowlayout i think
    ContentPane, i dont know what it holds...
    JScrollPane pane...this is hidden from view, unless I set the something JPanel to be hidden.
    Why cant i just see them all at the same time? I made sure the JPanel something had opque set to false, and now i can see the contentPane....but where are my g2d objects (located on "something")
    thanks...

  • Make a tooltip scroll with the component?

    Hi,
    I have a Canvas with many input fields so that Canvas is scrolling vertically. i have a default flex validation tooltips for the input fields, when i'm scrolling the canvas Tooltips are not scrolling.
    Is there any solution in Flex 3 for this problem?
    Thanks in advance,
    Sreedhar

    From you current code, your tooltip message is same for all the textinput. so but obviously , it will show you the same tooltip which
    indicates statitionary tooltip...
    Solution is created dynamic tooltip for each textbox for example
    message = "I have a tooltip!" + TextInput(e.currentTarget).id ;
    I mean to say any dynamic text which keep on changing with different textbox.
    Hope you got my point!!!

  • ScrollPane component smooth scrolling

    Hello. I just started working with AS 3.0 and I'm yet
    learning basics. I searched google and couldnt find the answer to
    my question; How to make scrolling on ScrollPane component smooth
    with AS 3.0? Please help.

    Hello. I just started working with AS 3.0 and I'm yet
    learning basics. I searched google and couldnt find the answer to
    my question; How to make scrolling on ScrollPane component smooth
    with AS 3.0? Please help.

  • Scrolling component into view programmatically without using javascript

    Hi,
    Is it possible to scroll an adf component into view programmatically without using javascript?
    I know of <af:scrollComponentIntoViewBehaviour> that can be added to a command component , but is there a way to do that programmatically in a bean?
    Problem with using javascript is its not guaranteed to work in different browsers.
    Regards,
    Rakesh.

    Hi John,
    Thanks for the reply.
    If i use the af:scrollComponentIntoViewBehavior, then i wont be able to achieve my desired functionality.
    In my use case, i want the id, of the component that needs to be scrolled into view, to be determined in the server listener of the button which is not happening.
    Code snippet in jspx page is as follows:
    <af:commandButton id="cb1" immediate="true">
    <af:clientListener method="clickButton" type="click"/>
    <af:serverListener type="customEvent"
    method="#{pageFlowScope.bean.doScroll }"/>
    <af:scrollComponentIntoViewBehavior id="#{pageFlowScope.bean.compId}/>
    </af:commandButton>
    And the java code for method doScroll is something like :
    public void doScroll (ClientEvent clientEvent)
    //logic to determine compId goes here
    compId = "id";
    So, the problem here is "compId" is set to some value when bean is loaded and the id in the af:scrollComponentIntoViewBehavior will be set to that value forever.
    I cant find any way of telling it to re-read the "compId" value, say after clicking the button. I can refresh the button in the server listener to update the compId .
    But the updated compId will come into picture from *next click*. This is because, after the button is clicked, "scroll" action happens first and then serverListener executes.
    Is there a way to change order of this execution like "execute server listener first and then do the scrolling thing" ?
    Regards,
    Rakesh.
    Edited by: 927925 on Jul 27, 2012 2:02 AM

  • ScrollPane scrolling

    Is there any way to capture the event when a user stops
    scrolling a scrollPane component. Right now I have actions set to
    take place when my scroll listener hears the user scrolling, but i
    have no way of stopping them once they let up/release the scroll
    bar. I thought to use an onRelease but that turned the entire thing
    into one big button that didnt let you scroll at all.

    Its kind of dumb how they have when that broadcasts when
    scrolling is going on but not one directly when its stops.
    Thanks for your help.
    Heres what i used:
    _root.onMouseUp = function () {
    if (_xmouse>=0 && _xmouse<=555 &&
    _ymouse>537 && _ymouse<558) {
    trace('stop that');
    }

  • Adding news ticker or text scroller in a jsf page

    Can anyone please give me some clue about adding news ticker or text scroller kind of component using jsf, richfaces or icefaces in which important information like information about available jobs can be shown?
    Thanks in advance.
    Edited by: 857452 on May 18, 2011 7:06 AM
    Edited by: 857452 on May 18, 2011 7:07 AM

    this is more the realm of javascript / ajax / DHTML, not JSF. JSF is server side, what you want to do is mostly client side. Only getting the data might involve the server.

Maybe you are looking for