在java中使用gui设计的问题

时间:2012-05-22 13:01:41

标签: java swing

我正在设计一个gui,它在一个面板上显示一个图像,并有一个滑块可以放大和缩小图像。但问题是:我的图像变焦但没有在滚动窗格 Scrollpane 中显示图像。

ImagePanel imageP = new ImagePanel("D:/ScannedImage1.jpg");
JSlider slid = (JSlider) evt.getSource();
float value = (float) slid.getValue();
imageP.setScale(value);
imagePanel.add(new JScrollPane(imageP), BorderLayout.CENTER);
imagePanel.validate();

代码用于imagePanel类的paintComponent方法

super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
    RenderingHints.VALUE_INTERPOLATION_BICUBIC);
int w = getWidth();
int h = getHeight();
int imageWidth = image.getWidth();
int imageHeight = image.getHeight();
double x = (w - scale * imageWidth) / 2;
double y = (h - scale * imageHeight) / 2;
AffineTransform at = AffineTransform.getTranslateInstance (x, y);
at.scale(scale, scale);
g2.drawRenderedImage(image, at);

2 个答案:

答案 0 :(得分:3)

由于JScrollPane依赖于客户端的首选尺寸,因此您可能需要以反映缩放尺寸的方式覆盖getPreferredSize() ImagePanel方法。

答案 1 :(得分:0)

不应该是:

imageP.add(new JScrollPane(), BorderLayout.CENTER);
imageP.validate();

如果没有,而你真的想直接从课堂上打电话,那么不应该是:

ImagePanel.add(new JScrollPane(), BorderLayout.CENTER);
ImagePanel.validate();

add()和validate()方法应该是静态的,否则你应该使用第一个例子。