我正在尝试在JScrollPane中编码可缩放图像.

当图像完全缩小时,它应该水平和垂直居中.当两个滚动条都出现时,变焦应该总是相对于鼠标坐标发生,即图像的相同点应该在缩放事件之前和之后的鼠标下面.

我几乎实现了我的目标.不幸的是,“scrollPane.getViewport().setViewPosition()”方法有时无法正确更新视图位置.在大多数情况下,调用该方法两次(黑客!)克服了这个问题,但视图仍然闪烁.

我没有解释为什么会这样.但是我相信这不是数学问题.

以下是MWE.要查看我的问题,您可以执行以下操作:

>放大直到你有一些滚动条(200%变焦左右)
>单击滚动条滚动到右下角
>将鼠标放在角落并放大两次.第二次你会看到滚动位置如何向中心跳跃.

如果有人能告诉我问题所在,我真的很感激.谢谢!

package com.vitco;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * Zoom-able scroll panel test case
 */
public class ZoomScrollPanel {

    // the size of our image
    private final static int IMAGE_SIZE = 600;

    // create an image to display
    private BufferedImage getimage() {
        BufferedImage image = new BufferedImage(IMAGE_SIZE,IMAGE_SIZE,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        // draw the small pixel first
        Random rand = new Random();
        for (int x = 0; x < IMAGE_SIZE; x += 10) {
            for (int y = 0; y < IMAGE_SIZE; y += 10) {
                g.setColor(new Color(rand.nextInt(255),rand.nextInt(255),rand.nextInt(255)));
                g.fillRect(x,y,10,10);
            }
        }
        // draw the larger transparent pixel second
        for (int x = 0; x < IMAGE_SIZE; x += 100) {
            for (int y = 0; y < IMAGE_SIZE; y += 100) {
                g.setColor(new Color(rand.nextInt(255),180));
                g.fillRect(x,100,100);
            }
        }
        return image;
    }

    // the image panel that resizes according to zoom level
    private class ImagePanel extends JPanel {
        private final BufferedImage image = getimage();

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g.create();
            g2.scale(scale,scale);
            g2.drawImage(image,null);
            g2.dispose();
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension((int)Math.round(IMAGE_SIZE * scale),(int)Math.round(IMAGE_SIZE * scale));
        }
    }

    // the current zoom level (100 means the image is shown in original size)
    private double zoom = 100;
    // the current scale (scale = zoom/100)
    private double scale = 1;

    // the last seen scale
    private double lastScale = 1;

    public void alignViewPort(Point mousePosition) {
        // if the scale didn't change there is nothing we should do
        if (scale != lastScale) {
            // compute the factor by that the image zoom has changed
            double scaleChange = scale / lastScale;

            // compute the scaled mouse position
            Point scaledMousePosition = new Point(
                    (int)Math.round(mousePosition.x * scaleChange),(int)Math.round(mousePosition.y * scaleChange)
            );

            // retrieve the current viewport position
            Point viewportPosition = scrollPane.getViewport().getViewPosition();

            // compute the new viewport position
            Point newViewportPosition = new Point(
                    viewportPosition.x + scaledMousePosition.x - mousePosition.x,viewportPosition.y + scaledMousePosition.y - mousePosition.y
            );

            // update the viewport position
            // IMPORTANT: This call doesn't always update the viewport position. If the call is made twice
            // it works correctly. However the screen still "flickers".
            scrollPane.getViewport().setViewPosition(newViewportPosition);

            // debug
            if (!newViewportPosition.equals(scrollPane.getViewport().getViewPosition())) {
                System.out.println("Error: " + newViewportPosition + " != " + scrollPane.getViewport().getViewPosition());
            }

            // remember the last scale
            lastScale = scale;
        }
    }

    // reference to the scroll pane container
    private final JScrollPane scrollPane;

    // constructor
    public ZoomScrollPanel() {
        // initialize the frame
        JFrame frame = new JFrame();
        frame.setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(600,600);

        // initialize the components
        final ImagePanel imagePanel = new ImagePanel();
        final JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new GridBagLayout());
        centerPanel.add(imagePanel);
        scrollPane = new JScrollPane(centerPanel);
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        frame.add(scrollPane);

        // add mouse wheel listener
        imagePanel.addMouseWheelListener(new MouseAdapter() {
            @Override
            public void mouseWheelMoved(MouseWheelEvent e) {
                super.mouseWheelMoved(e);
                // check the rotation of the mousewheel
                int rotation = e.getWheelRotation();
                boolean zoomed = false;
                if (rotation > 0) {
                    // only zoom out until no scrollbars are visible
                    if (scrollPane.getHeight() < imagePanel.getPreferredSize().getHeight() ||
                            scrollPane.getWidth() < imagePanel.getPreferredSize().getWidth()) {
                        zoom = zoom / 1.3;
                        zoomed = true;
                    }
                } else {
                    // zoom in until maximum zoom size is reached
                    double newCurrentZoom = zoom * 1.3;
                    if (newCurrentZoom < 1000) { // 1000 ~ 10 times zoom
                        zoom = newCurrentZoom;
                        zoomed = true;
                    }
                }
                // check if a zoom happened
                if (zoomed) {
                    // compute the scale
                    scale = (float) (zoom / 100f);

                    // align our viewport
                    alignViewPort(e.getPoint());

                    // invalidate and repaint to update components
                    imagePanel.revalidate();
                    scrollPane.repaint();
                }
            }
        });

        // display our frame
        frame.setVisible(true);
    }

    // the main method
    public static void main(String[] args) {
        new ZoomScrollPanel();
    }
}

注意:我也在这里查看了JScrollPane setViewPosition After “Zoom”的问题,但不幸的是问题和解决方案略有不同,不适用.

编辑

我已经通过使用hack解决了这个问题,但是我仍然没有更接近理解底层问题是什么.发生的事情是,当调用setViewPosition时,某些内部状态更改会触发对setViewPosition的其他调用.这些额外的呼叫偶尔会发生.当我阻止它们时,一切都很完美.

为了解决这个问题,我简单介绍了一个新的布尔变量“blocked = false;”并替换了线

scrollPane = new JScrollPane(centerPanel);

scrollPane.getViewport().setViewPosition(newViewportPosition);

scrollPane = new JScrollPane();

    scrollPane.setViewport(new JViewport() {
        private boolean inCall = false;
        @Override
        public void setViewPosition(Point pos) {
            if (!inCall || !blocked) {
                inCall = true;
                super.setViewPosition(pos);
                inCall = false;
            }
        }
    });

    scrollPane.getViewport().add(centerPanel);

blocked = true;
     scrollPane.getViewport().setViewPosition(newViewportPosition);
     blocked = false;

如果有人能理解这一点,我仍然会非常感激!

为什么这个黑客工作?有没有更简洁的方法来实现相同的功能?

解决方法

这是完整的,功能齐全的代码.我仍然不明白为什么黑客是必要的,但至少它现在按预期工作:
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseWheelEvent;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * Zoom-able scroll panel
 */
public class ZoomScrollPanel {

    // the size of our image
    private final static int IMAGE_SIZE = 600;

    // create an image to display
    private BufferedImage getimage() {
        BufferedImage image = new BufferedImage(IMAGE_SIZE,(int)Math.round(IMAGE_SIZE * scale));
        }
    }

    // the current zoom level (100 means the image is shown in original size)
    private double zoom = 100;
    // the current scale (scale = zoom/100)
    private double scale = 1;

    // the last seen scale
    private double lastScale = 1;

    // true if currently executing setViewPosition
    private boolean blocked = false;

    public void alignViewPort(Point mousePosition) {
        // if the scale didn't change there is nothing we should do
        if (scale != lastScale) {
            // compute the factor by that the image zoom has changed
            double scaleChange = scale / lastScale;

            // compute the scaled mouse position
            Point scaledMousePosition = new Point(
                    (int)Math.round(mousePosition.x * scaleChange),viewportPosition.y + scaledMousePosition.y - mousePosition.y
            );

            // update the viewport position
            blocked = true;
            scrollPane.getViewport().setViewPosition(newViewportPosition);
            blocked = false;

            // remember the last scale
            lastScale = scale;
        }
    }

    // reference to the scroll pane container
    private final JScrollPane scrollPane;

    // constructor
    public ZoomScrollPanel() {
        // initialize the frame
        JFrame frame = new JFrame();
        frame.setDefaultCloSEOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setSize(600,600);

        // initialize the components
        final ImagePanel imagePanel = new ImagePanel();
        final JPanel centerPanel = new JPanel();
        centerPanel.setLayout(new GridBagLayout());
        centerPanel.add(imagePanel);
        scrollPane = new JScrollPane();

        scrollPane.setViewport(new JViewport() {
            private boolean inCall = false;
            @Override
            public void setViewPosition(Point pos) {
                if (!inCall || !blocked) {
                    inCall = true;
                    super.setViewPosition(pos);
                    inCall = false;
                }
            }
        });

        scrollPane.getViewport().add(centerPanel);
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);
        frame.add(scrollPane);

        // add mouse wheel listener
        imagePanel.addMouseWheelListener(new MouseAdapter() {
            @Override
            public void mouseWheelMoved(MouseWheelEvent e) {
                super.mouseWheelMoved(e);
                // check the rotation of the mousewheel
                int rotation = e.getWheelRotation();
                boolean zoomed = false;
                if (rotation > 0) {
                    // only zoom out until no scrollbars are visible
                    if (scrollPane.getHeight() < imagePanel.getPreferredSize().getHeight() ||
                            scrollPane.getWidth() < imagePanel.getPreferredSize().getWidth()) {
                        zoom = zoom / 1.3;
                        zoomed = true;
                    }
                } else {
                    // zoom in until maximum zoom size is reached
                    double newCurrentZoom = zoom * 1.3;
                    if (newCurrentZoom < 1000) { // 1000 ~ 10 times zoom
                        zoom = newCurrentZoom;
                        zoomed = true;
                    }
                }
                // check if a zoom happened
                if (zoomed) {
                    // compute the scale
                    scale = (float) (zoom / 100f);

                    // align our viewport
                    alignViewPort(e.getPoint());

                    // invalidate and repaint to update components
                    imagePanel.revalidate();
                    scrollPane.repaint();
                }
            }
        });

        // display our frame
        frame.setVisible(true);
    }

    // the main method
    public static void main(String[] args) {
        new ZoomScrollPanel();
    }
}

java – Zoomable JScrollPane – setViewPosition无法更新的更多相关文章

  1. css绝对定位如何在不同分辨率下的电脑正常显示定位位置?(一定要看!)

    这篇文章主要介绍了css绝对定位如何在不同分辨率下的电脑正常显示定位位置,本文首先解释了常见的电脑分辨率,为了页面在不同的分辨率下正常显示,要给页面一个安全宽度,再去使用绝对定位,具体操作步骤大家可查看下文的详细讲解,感兴趣的小伙伴们可以参考一下。

  2. 正则表达式可视化工具

    Index.htmlcommon.cssmain.jsdraw.jsMeta.js运行结果如图:

  3. centos discuz论坛环境搭建

    >然后在编辑模式下摁键盘esc退出编辑模式,回到控制模式,在控制模式下摁键盘:,再输入wq然后回车。如何使用winscp软件这里不再赘述了。

  4. angularjs – Angular-google-map界限示例

    没弄明白怎么做.我有一堆标记,我手动计算东北和西南点.但它看起来没有效果;(期待一个如何使用边界的例子.谢谢.HTML:JS:我认为问题可能是变焦.从逻辑上讲,缩放概念不会与边界相关,因为边界定义了缩放.

  5. angularjs – 角谷地图搜索功能的工作示例

    /api如果你写的东西确实找到它在一个下拉列表中,但是当你按回车,地图没有回应。–当您输入时,如何使地图移动到正确的位置?

  6. javascript – 如何获取JqueryUI可以使用缩放/缩放 – 鼠标移动进行排序

    我正在尝试使用JqueryUISortable进行缩放.问题是鼠标不会像拖动的元素一样移动.有很多关于如何使用Draggable工作的例子.以下是Draggable项目的解决方法示例:http://jsfiddle.net/TqUeS/660/我希望Drag事件可以在Sortable版本的Sort事件中被替换,但是从下面的小提琴中可以看出它不起作用.在sort事件中设置ui.position没有任

  7. Angular 图片裁剪上传插件

    本文将介绍基于Angular的图片裁剪上传插件。而不同于我们通常所见到的拖动剪裁范围,进行的图片剪裁。这是一种反向思维。imgZoomCanvas.js图片的放大、缩小、拖动,全部是在html5的Canvas上面完成的。imgZoomCanvas开放出了四个方法:imgUploader.js接下来介绍imgUpload这个directive,就是上面那个GIF看到的图片上传组件。逻辑代码封装在imgUploader.js里面你可以自己定制这四个方法:另外该directive开放出一个回调方法onUploa

  8. java – Zoomable JScrollPane – setViewPosition无法更新

    注意:我也在这里查看了JScrollPanesetViewPositionAfter“Zoom”的问题,但不幸的是问题和解决方案略有不同,不适用.编辑我已经通过使用hack解决了这个问题,但是我仍然没有更接近理解底层问题是什么.发生的事情是,当调用setViewPosition时,某些内部状态更改会触发对setViewPosition的其他调用.这些额外的呼叫偶尔会发生.当我阻止它们时,一切都很完美.为了解决这个问题,我简单介绍了一个新的布尔变量“blocked=false;”并替换了线和同和如果有人能理

  9. 如何调用AngularJS指令中定义的方法?

    我有一个指令,这里是代码:我想对一个用户操作调用updateMap()。从控制器调用updateMap()的最好方法是什么?如果要使用隔离的范围,可以使用控制器作用域中的变量的双向绑定传递控制对象。还可以使用相同的控件对象在一个页面上控制同一指令的几个实例。

  10. javascript – 如何使谷歌地图默认指向美国?

    在onload事件中我想加载一个谷歌地图来显示美国.我需要在选项{}中添加什么值?解决方法将其定位到美国的纬度和经度,并调整缩放.在Google地图上搜索某个地点后,您可以在大多数浏览器中添加在地址栏中获取纬度和经度坐标或者您可以使用名为“USA”的反向地理编码,如下所示:

随机推荐

  1. 基于EJB技术的商务预订系统的开发

    用EJB结构开发的应用程序是可伸缩的、事务型的、多用户安全的。总的来说,EJB是一个组件事务监控的标准服务器端的组件模型。基于EJB技术的系统结构模型EJB结构是一个服务端组件结构,是一个层次性结构,其结构模型如图1所示。图2:商务预订系统的构架EntityBean是为了现实世界的对象建造的模型,这些对象通常是数据库的一些持久记录。

  2. Java利用POI实现导入导出Excel表格

    这篇文章主要为大家详细介绍了Java利用POI实现导入导出Excel表格,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  3. Mybatis分页插件PageHelper手写实现示例

    这篇文章主要为大家介绍了Mybatis分页插件PageHelper手写实现示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  4. (jsp/html)网页上嵌入播放器(常用播放器代码整理)

    网页上嵌入播放器,只要在HTML上添加以上代码就OK了,下面整理了一些常用的播放器代码,总有一款适合你,感兴趣的朋友可以参考下哈,希望对你有所帮助

  5. Java 阻塞队列BlockingQueue详解

    本文详细介绍了BlockingQueue家庭中的所有成员,包括他们各自的功能以及常见使用场景,通过实例代码介绍了Java 阻塞队列BlockingQueue的相关知识,需要的朋友可以参考下

  6. Java异常Exception详细讲解

    异常就是不正常,比如当我们身体出现了异常我们会根据身体情况选择喝开水、吃药、看病、等 异常处理方法。 java异常处理机制是我们java语言使用异常处理机制为程序提供了错误处理的能力,程序出现的错误,程序可以安全的退出,以保证程序正常的运行等

  7. Java Bean 作用域及它的几种类型介绍

    这篇文章主要介绍了Java Bean作用域及它的几种类型介绍,Spring框架作为一个管理Bean的IoC容器,那么Bean自然是Spring中的重要资源了,那Bean的作用域又是什么,接下来我们一起进入文章详细学习吧

  8. 面试突击之跨域问题的解决方案详解

    跨域问题本质是浏览器的一种保护机制,它的初衷是为了保证用户的安全,防止恶意网站窃取数据。那怎么解决这个问题呢?接下来我们一起来看

  9. Mybatis-Plus接口BaseMapper与Services使用详解

    这篇文章主要为大家介绍了Mybatis-Plus接口BaseMapper与Services使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

  10. mybatis-plus雪花算法增强idworker的实现

    今天聊聊在mybatis-plus中引入分布式ID生成框架idworker,进一步增强实现生成分布式唯一ID,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

返回
顶部