开发者

How to adjust scrollbar with image zoomIN and zoomOUT in Swing

I want to adjust scrollbar when image zoomIN and zoomOUT, My image display on JPan开发者_开发知识库el and JScrollpane contains JPanel.


For your updated question:

You need to call setPreferredSize with your new image size (tested your application with this).

Change in both zoomIN and zoomOut from:

can.setSize(imgSize);

To:

can.setPreferredSize(imgSize);

Example

You need to update the preferred size on slider changes. I wrote a small program (code below) that produces this screenshot (with zoom control):

How to adjust scrollbar with image zoomIN and zoomOUT  in Swing


Image Component code:

static class ImageComponent extends JComponent {

    final BufferedImage img;

    public ImageComponent(URL url) throws IOException {
        img = ImageIO.read(url);
        setZoom(1);
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Dimension dim = getPreferredSize();
        g.drawImage(img, 0, 0, dim.width, dim.height, this);
    }

    private void setZoom(double zoom) {
        int w = (int) (zoom * img.getWidth());
        int h = (int) (zoom * img.getHeight());
        setPreferredSize(new Dimension(w, h));
        revalidate();
        repaint();
    }
}

Main program:

public static void main(String[] args) throws Exception {

    final URL lenna =
        new URL("http://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png");

    final JSlider slider = new JSlider(0, 1000, 500);
    final ImageComponent image = new ImageComponent(lenna);
    slider.addChangeListener(new ChangeListener() {
        @Override
        public void stateChanged(ChangeEvent e) {
            image.setZoom(2. * slider.getValue() / slider.getMaximum());
        }
    });

    JFrame frame = new JFrame("Test");
    frame.add(slider, BorderLayout.NORTH);

    frame.add(new JScrollPane(image));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
}


You should adapt the preferred size of the JPanel according to visible image size changes.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜