package demo;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Test{
public static void main(String[] args){
new MyFrame();
}
}
class MyFrame extends JFrame{
BufferedImage picture;
PictureBox pictureBox;
MyFrame(){
try{
picture = ImageIO.read(new File("C:/Users/GGFlyme/Desktop/2.jpg"));
}catch(IOException e){
e.printStackTrace();
}
initComponent();
}
void initComponent(){
pictureBox = new PictureBox(picture);
Container container = getContentPane();
container.setLayout(null);
container.add(pictureBox);
setSize(800,600);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setVisible(true);
}
}
class PictureBox extends JPanel{
static float scalingK = 0.04f;
static float scalingMax = 8.0f;
static float scalingMin = 0.08f;
BufferedImage picture;
int picWidth;
int picHeight;
boolean isLeftMouseButtonPressed;
int mousePressedX;
int mousePressedY;
int mouseX;
int mouseY;
float scaling = 1.0f;
public PictureBox(BufferedImage img){
picture = img;
picWidth = picture.getWidth();
picHeight = picture.getHeight();
setBounds(0,0,picWidth,picHeight);
initAdapterAndListener();
}
void initAdapterAndListener(){
addMouseListener(new MouseAdapter(){
@Override
public void mousePressed(MouseEvent e){
if(e.getButton() == 1){
mousePressedX = e.getX();
mousePressedY = e.getY();
isLeftMouseButtonPressed = true;
}
}
@Override
public void mouseReleased(MouseEvent e){
if(e.getButton() == 1){
mousePressedX = e.getX();
mousePressedY = e.getY();
isLeftMouseButtonPressed = false;
}
}
});
addMouseMotionListener(new MouseAdapter(){
@Override
public void mouseDragged(MouseEvent e){
if(isLeftMouseButtonPressed){
setLocation(getX() + e.getX() - mousePressedX,getY() + e.getY() - mousePressedY);
}
}
});
addMouseWheelListener(new MouseAdapter(){
@Override
public void mouseWheelMoved(MouseWheelEvent e){
mouseX = e.getX();
mouseY = e.getY();
if(e.getWheelRotation() > 0){
scaling += scalingK;
scaling = Math.min(scalingMax,scaling);
} else{
scaling -= scalingK;
scaling = Math.max(scalingMin,scaling);
}
repaint();
}
});
}
@Override
public void paint(Graphics g){
int w0 = getWidth();
int h0 = getHeight();
int w = (int)(picWidth * scaling);
int h = (int)(picHeight * scaling);
int left = getX();
int top = getY();
setBounds((int)(mouseX * (1 - (float)w / w0)) + left,(int)(mouseY * (1 - (float)h / h0)) + top,w,h);
g.drawImage(picture,0,0,w,h,null);
}
}