How to adjust the scroll bar using the images zoomin and zoomout in swing
•
Java
I want to adjust the scroll bar when the images zoom in and zoom out. My image display on JPanel and JScrollPane contains JPanel
Solution
For your updated questions:
You need to call setpreferredsize with the new image size (use this to test your application)
Change zoomin and zoomout from:
can.setSize(imgSize);
To:
can.setPreferredSize(imgSize);
example
You need to update the slider to change the preferred size I wrote a small program (the following code) to generate this screenshot (with zoom control):
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,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);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
