/**
*
*/
package de.tutorials;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;
/**
* @author Tom
*
*/
public class JScrollPaneCenterExample extends JFrame {
public JScrollPaneCenterExample() {
super("JScrollPaneCenterExample");
setDefaultCloseOperation(EXIT_ON_CLOSE);
final JPanel panel = new JPanel() {
Image image;
{
try {
image = ImageIO.read(new File("c:/Sonnenuntergang.jpg"))
.getScaledInstance(1600, 1200,
BufferedImage.SCALE_SMOOTH);
} catch (IOException e) {
e.printStackTrace();
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
g.drawLine(0, getHeight() / 2, getWidth(), getHeight() / 2);
g.drawLine(getWidth() / 2, 0, getWidth() / 2, getHeight());
}
};
panel.setPreferredSize(new Dimension(1600, 1200));
final JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.setPreferredSize(new Dimension(640, 480));
scrollPane.addMouseListener(new MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent e) {
Point point = e.getPoint();
JViewport viewport = scrollPane.getViewport();
Point viewPosition = viewport.getViewPosition();
int middleX = viewport.getWidth() / 2;
int middleY = viewport.getHeight() / 2;
int dx = point.x - middleX;
int dy = point.y - middleY;
viewPosition.translate(dx, dy);
adjustPositionBounds(viewPosition, viewport);
viewport.setViewPosition(viewPosition);
}
private void adjustPositionBounds(Point viewPosition,
JViewport viewport) {
System.out.println(viewPosition);
if (viewPosition.x < 0) {
viewPosition.x = 0;
}
if (viewPosition.x + viewport.getWidth() > panel.getWidth()) {
viewPosition.x = panel.getWidth() - viewport.getWidth();
}
if (viewPosition.y < 0) {
viewPosition.y = 0;
}
if (viewPosition.y + viewport.getHeight() > panel.getHeight()) {
viewPosition.y = panel.getHeight() - viewport.getHeight();
}
}
});
add(scrollPane);
pack();
setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
new JScrollPaneCenterExample();
}
}