Java tutorial
//package com.java2s; /* * Copyright 2003,2004,2005 Colin Crist * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ import java.awt.Component; import java.awt.Container; import java.awt.Rectangle; import javax.swing.JComponent; import javax.swing.JViewport; public class Main { public static final int VIEWPORT = 0, // take the policy of the viewport UNCHANGED = 1, // don't scroll if it fills the visible area, otherwise // take the policy of the viewport FIRST = 2, // scroll the first part of the region into view CENTER = 3, // center the region LAST = 4; public static void scrollHorizontally(JComponent c, Rectangle r) { scrollHorizontally(c, r.x, r.x + r.width); } public static void scrollHorizontally(JComponent c, int from, int to) { Rectangle visible = c.getVisibleRect(); if (visible.x <= from && visible.x + visible.width >= to) return; visible.x = from; visible.width = to - from; c.scrollRectToVisible(visible); } public static void scrollHorizontally(JComponent c, Rectangle r, int bias) { scrollHorizontally(c, r.x, r.x + r.width, bias); } public static void scrollHorizontally(JComponent c, int from, int to, int bias) { Rectangle visible = c.getVisibleRect(), dest = new Rectangle(visible); dest.x = from; dest.width = to - from; if (dest.width > visible.width) { if (bias == VIEWPORT) { // leave as is } else if (bias == UNCHANGED) { if (dest.x <= visible.x && dest.x + dest.width >= visible.x + visible.width) { dest.x = visible.x; dest.width = visible.width; } } else { if (bias == CENTER) dest.x += (dest.width - visible.width) / 2; else if (bias == LAST) dest.x += dest.width - visible.width; dest.width = visible.width; } } if (!visible.contains(dest)) c.scrollRectToVisible(dest); } public static void scrollRectToVisible(Component component, Rectangle aRect) { Container parent; int dx = component.getX(), dy = component.getY(); for (parent = component.getParent(); parent != null && (!(parent instanceof JViewport) || (((JViewport) parent) .getClientProperty("HierarchicalTable.mainViewport") == null)); parent = parent .getParent()) { Rectangle bounds = parent.getBounds(); dx += bounds.x; dy += bounds.y; } if (parent != null) { aRect.x += dx; aRect.y += dy; ((JComponent) parent).scrollRectToVisible(aRect); aRect.x -= dx; aRect.y -= dy; } } }