Example usage for javax.swing JViewport getVisibleRect

List of usage examples for javax.swing JViewport getVisibleRect

Introduction

In this page you can find the example usage for javax.swing JViewport getVisibleRect.

Prototype

@BeanProperty(bound = false)
public Rectangle getVisibleRect() 

Source Link

Document

Returns the Component's "visible rectangle" - the intersection of this component's visible rectangle, new Rectangle(0, 0, getWidth(), getHeight()), and all of its ancestors' visible rectangles.

Usage

From source file:Main.java

public static void main(String[] args) {
    int ROWS = 100;
    JPanel content = new JPanel();
    content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS));
    content.add(new JLabel("Thanks for helping out. Use tab to move around."));
    for (int i = 0; i < ROWS; i++) {
        JTextField field = new JTextField("" + i);
        field.setName("field#" + i);
        content.add(field);//from  ww  w  .j a v  a 2 s  .  c om
    }
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner",
            new PropertyChangeListener() {
                @Override
                public void propertyChange(PropertyChangeEvent evt) {
                    if (!(evt.getNewValue() instanceof JComponent)) {
                        return;
                    }
                    JViewport viewport = (JViewport) content.getParent();
                    JComponent focused = (JComponent) evt.getNewValue();
                    if (content.isAncestorOf(focused)) {
                        Rectangle rect = focused.getBounds();
                        Rectangle r2 = viewport.getVisibleRect();
                        content.scrollRectToVisible(
                                new Rectangle(rect.x, rect.y, (int) r2.getWidth(), (int) r2.getHeight()));
                    }
                }
            });
    JFrame window = new JFrame();
    window.setContentPane(new JScrollPane(content));
    window.setSize(200, 200);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setVisible(true);
}