Results 1 to 2 of 2
  1. #1
    berkeleybross's Avatar
    berkeleybross is offline Senior Member
    Join Date
    Feb 2010
    Location
    England
    Posts
    187
    Rep Power
    5

    Default Scrolling to focused component

    Hey all,
    Im trying to make a scroll pane scroll to a component when it receives focus, to make sure that it is fully visible to the user.

    I'm currently adding this code to every component:
    Java Code:
            myComponent.addFocusListener(new java.awt.event.FocusAdapter() {
                @Override
                public void focusGained(java.awt.event.FocusEvent evt) {
                    jComponentFocusGained(evt);
                }
            });
    where focusGained is in a class which extends JPanel:
    Java Code:
        private void jComponentFocusGained(java.awt.event.FocusEvent evt) {
            java.awt.Component focusedComponent = evt.getComponent();
            scrollRectToVisible(focusedComponent.getBounds());
            repaint();
        }
    Now the problem is that these components are in different jPanels which are in the scroll pane, so the getBounds() method is returning x and y values of 0 for some components - so the scroll pane scrolls to the top of the page.

    How do i get around this?

    I tried changing jComponentFocusGained to
    Java Code:
    focusedComponent.getParent().scrollRectToVisible(focusedComponent.getBounds());
    but that doesnt compile.

    Thanks for your attention,

    Berkeleybross

  2. #2
    berkeleybross's Avatar
    berkeleybross is offline Senior Member
    Join Date
    Feb 2010
    Location
    England
    Posts
    187
    Rep Power
    5

    Default

    Ok solved this just now.
    I removed the method jComponentFocusGained, and simply used

    Java Code:
            myComponent.addFocusListener(new java.awt.event.FocusAdapter() {
                @Override
                public void focusGained(java.awt.event.FocusEvent evt) {
                    myComponent.scrollRectToVisible(myComponent.getBounds());
                    repaint();
                }
            });
    It requires a bit more effort in copy and pasting but at least it works :P

    Berkeleybross

Similar Threads

  1. Scrolling problem
    By lethalwire in forum Eclipse
    Replies: 5
    Last Post: 06-27-2010, 12:37 PM
  2. Side-scrolling
    By shadycharacter in forum New To Java
    Replies: 0
    Last Post: 04-21-2010, 05:20 PM
  3. Last focused component
    By Gajesh Tripathi in forum AWT / Swing
    Replies: 2
    Last Post: 11-21-2009, 06:45 PM
  4. how to make window active and textfield focused
    By whwillisiv in forum New To Java
    Replies: 0
    Last Post: 04-28-2009, 05:06 AM
  5. AWT Table Scrolling
    By albert_kam in forum AWT / Swing
    Replies: 0
    Last Post: 01-03-2008, 12:37 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •