我想要在我的JFrame和applet上显示一个非常大的图像,JFrame / Applet的大小是765x503,但图像更大。我需要一种以实际尺寸显示图像的方法。我怎样才能做到这一点,我可以移动屏幕来显示一些图像,并能够在图像周围移动?
我希望能够拖动屏幕,而不是使用滚动条。
答案 0 :(得分:1)
JScrollPane可能是您需要的......添加垂直和水平滚动
答案 1 :(得分:0)
基本思路是你需要提供一些应该应用于要绘制的图像的偏移。
当用户在图像上的某个点按下鼠标按钮时,您会记录点击点。当拖动鼠标时,你差异化了。这为您提供了移动偏移量。根据原始位置,您只需将此差异添加到并生成新的偏移量。
还有其他方法可以做到,但一般来说,这是我使用的方法。
我还添加了代码来检查拖动是否会使图像超出可视区域的范围,您必须决定是否要使用它...
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
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.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class BigImage {
public static void main(String[] args) {
new BigImage();
}
public BigImage() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private BufferedImage bg;
private Point offset = new Point(0, 0);
public TestPane() {
try {
bg = ImageIO.read(new File("/path/to/image"));
} catch (IOException ex) {
ex.printStackTrace();
}
MouseAdapter ma = new MouseAdapter() {
private Point clickPoint;
private Point origin;
@Override
public void mousePressed(MouseEvent e) {
setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
clickPoint = e.getPoint();
origin = new Point(offset);
}
@Override
public void mouseReleased(MouseEvent e) {
setCursor(Cursor.getDefaultCursor());
clickPoint = null;
}
@Override
public void mouseDragged(MouseEvent e) {
int x = e.getPoint().x - clickPoint.x;
int y = e.getPoint().y - clickPoint.y;
offset.x = origin.x + x;
offset.y = origin.y + y;
if (offset.x > 0) {
offset.x = 0;
}
if (offset.x + bg.getWidth() < getWidth()) {
offset.x = -bg.getWidth() + getWidth();
}
if (offset.y > 0) {
offset.y = 0;
}
if (offset.y + bg.getHeight() < getHeight()) {
offset.y = -bg.getHeight() + getHeight();
}
repaint();
}
};
addMouseListener(ma);
addMouseMotionListener(ma);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(800, 600);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (bg != null) {
Graphics2D g2d = (Graphics2D) g.create();
g2d.drawImage(bg, offset.x, offset.y, this);
g2d.dispose();
}
}
}
}