java swing 实现鼠标滑轮聚焦缩放图片

1.直接上代码

import java.awt. * ;
import java.awt.event. * ;
import java.awt.geom. * ; 
import javax.swing. * ;
public class FPanel extends javax.swing.JPanel {
	private Dimension preferredSize = new Dimension( 400 , 400 ); 
	private Rectangle2D[] rects = new Rectangle2D[ 50 ]; 
	public static void main(String[] args) { 
		JFrame jf = new JFrame( " test " ); 
		jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
		jf.setSize( 400 , 400 ); 
		jf.add( new JScrollPane( new FPanel())); 
		jf.setVisible( true ); 
	} 
	public FPanel() { 
	// generate rectangles with pseudo-random coords 
		for ( int i = 0 ; i < rects.length; i ++ ) { 
			rects[i] = new Rectangle2D.Double(Math.random()*.8 , Math.random()*.8 , Math.random()*.2 , Math.random()*.2 ); 
			} 
	// mouse listener to detect scrollwheel events 
	addMouseWheelListener( new MouseWheelListener() {
			public void mouseWheelMoved(MouseWheelEvent e) {
				updatePreferredSize(e.getWheelRotation(), e.getPoint()); 
			} }); 
	}
	private void updatePreferredSize( int wheelRotation, Point stablePoint) { 
		double scaleFactor = findScaleFactor(wheelRotation); 
		scaleBy(scaleFactor); 
		Point offset = findOffset(stablePoint, scaleFactor); 
		offsetBy(offset); getParent().doLayout();
	} 
	private double findScaleFactor( int wheelRotation) { 
		double d= wheelRotation*1.08 ; return (d > 0 ) ? 1/d : -d; 
	} 
	private void scaleBy( double scaleFactor) { 
		int w = ( int ) (getWidth()*scaleFactor);
		int h = ( int ) (getHeight()*scaleFactor);
		preferredSize.setSize(w, h); 
	} 
	private Point findOffset(Point stablePoint, double scaleFactor) {
		int x = ( int ) (stablePoint.x*scaleFactor)-stablePoint.x; 
		int y = ( int ) (stablePoint.y*scaleFactor)-stablePoint.y;
		return new Point(x, y); 
	} 
	private void offsetBy(Point offset) { 
		Point location = getLocation();
		setLocation(location.x - offset.x, location.y - offset.y);
	} 
	public Dimension getPreferredSize() { 
		return preferredSize;
	}
	private Rectangle2D r = new Rectangle2D.Float();
	public void paint(Graphics g) { 
		super.paint(g); g.setColor(Color.red);
		int w = getWidth(); int h = getHeight(); 
		for (Rectangle2D rect : rects) {
			r.setRect(rect.getX()*w,rect.getY()*h,rect.getWidth()*w,rect.getHeight()*h);
			((Graphics2D) g).draw(r); 
		} 
	}
}

2.运行效果

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值