我想在图像zoomIN和zoomOUT时调整滚动条,JPanel和JScrollpane上的我的图像显示包含JPanel。
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);
You need to update the preferred size on slider changes. I wrote a small program (code below) that produces 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, 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);
}
您应该根据可见的图像大小更改调整JPanel的首选大小。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.