JAVA~怎么把1个图放在正中间。。。
发布网友
发布时间:2022-04-30 02:28
我来回答
共1个回答
热心网友
时间:2022-06-29 07:47
//滚动滚轮进行放大缩小。
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class ScaleImageTest extends JFrame {
public ScaleImageTest() {
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(500, 400);
Image image = Toolkit.getDefaultToolkit().getImage("disk.jpg");//TODO:改成你自己的图片。
panel = new ScaleImagePanel(image, 1);
this.add(panel, BorderLayout.CENTER);
this.addMouseWheelListener(new MouseWheelListener() {//TODO:改成你自己期望的事件*。
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
int rotation = e.getWheelRotation();
System.out.println(rotation);
double newpro=panel.getProportion()+INC*rotation;
if(newpro<ScaleImagePanel.MIN_PRO||
newpro>ScaleImagePanel.MAX_PRO)
return;
panel.setProportion(newpro);
}
});
}
private static final double INC = 0.25;
private ScaleImagePanel panel;
public static final class ScaleImagePanel extends JComponent {
public ScaleImagePanel(Image image, int proportion) {
this.setImage(image);
this.setProportion(proportion);
}
public double getProportion() {
return proportion;
}
public void setProportion(double proportion) {
if (proportion < MIN_PRO || proportion > MAX_PRO)
throw new IllegalArgumentException("Proportion must be in [ "
+ MIN_PRO + ", " + MAX_PRO + "]");
this.proportion = proportion;
this.validate();
this.repaint();
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
@Override
public Dimension getPreferredSize() {
return new Dimension((int) (image.getWidth(this) * proportion),
(int) (image.getHeight(this) * proportion));
}
@Override
protected void paintComponent(Graphics g) {
Dimension size = getSize();
Dimension presize = getPreferredSize();
int x = (size.width - presize.width) / 2;
int y = (size.height - presize.height) / 2;
g.drawImage(image, x, y, presize.width, presize.height, this);
}
private double proportion = 1;
private Image image;
private static final double MAX_PRO = 8;
private static final double MIN_PRO = 0.25;
}
/**
* @param args
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
new ScaleImageTest().setVisible(true);
}
});
}
}