paintComponent()的问题

时间:2015-04-17 13:36:25

标签: java swing paintcomponent repaint

public class ImagePreview extends JPanel {

    private static final long serialVersionUID = 1L;
    final float ratio = 1.0f;
    private RenderedImage image;

    public ImagePreview (int imgWidth, int imgHeight) {

        this.setPreferredSize(new Dimension((int) (ratio * imgWidth) + 5, (int) (ratio * imgHeight) + 5));
    }

    public ImagePreview (int imgWidth, int imgHeight, final RenderedImage image) {
        super();
        this.setPreferredSize(new Dimension((int) (ratio * imgWidth) + 5, (int) (ratio * imgHeight) + 5));
        this.image = image; 
        repaint();
    }

    @Override
    public synchronized void paintComponent(Graphics g) {
        super.paintComponent(g);
        VectorGraphics g2 = VectorGraphics.create(g);
        if (image != null) {
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            g2.drawRenderedImage(image, AffineTransform.getScaleInstance(ratio, ratio));
        }
    }
}

单击按钮调用此方法     //调用此方法     ImagePreview cart = new ImagePreview(imgWidth,imgHeight,image);

我正在获取图像,但它没有在Panel上重新绘制。我无法确定背后的原因

1 个答案:

答案 0 :(得分:1)

  

但我只是想为图像创建一个预览面板

当您进行自定义绘制时,您需要覆盖面板的getPreferredSize()方法以返回图像的大小,否则大小为(0,0),因此无需绘制任何内容。

VectorGraphics g2 = VectorGraphics.create(g);

不要使用第三方课程发布代码。我们不知道您的代码或课程是否存在问题。

如果您需要更多帮助,请发布显示问题的正确SSCCE