使用drawImage在JPanel中绘制图像

时间:2017-06-22 15:16:35

标签: java swing jpanel drawimage

我可以请你帮忙吗?我在JPanel中绘制图像时遇到了一些麻烦。我曾经创建了一个扩展JPanel的类并且做了这个

public class Example extends JPanel {

    BufferedImage background;

    public Example () {

        background = loadImage();   
    }           

    private BufferedImage loadImage(){
        URL imagePath = getClass().getResource("Immagini/Board.png");
        BufferedImage result = null;
        try {
            result = ImageIO.read(imagePath);
        } catch (IOException e) {
            System.err.println("Errore, immagine non trovata");
        }

        return result;
    }

     @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Dimension size = getSize();
        g.drawImage(background, 0, 0,size.width, size.height,0, 0, background.getWidth(), background.getHeight(), null);

    }
}

它很完美,现在我不能这样做,因为我的newExample类扩展了genericExample,因此也无法扩展JPanel。我在newExample中有JPanel panel = new JPanel(),我想在上面的代码中绘制,我如何调整它以适应这种不同的情况?

1 个答案:

答案 0 :(得分:1)

您仍然可以重复使用Example课程。您将使用覆盖的面板类而不是JPanel panel = new JPanel();

JPanel panel = new Example();

另一种方法是使用JPanel的匿名实现:

JPanel panel = new JPanel(){
    BufferedImage background = loadImage();

    private BufferedImage loadImage(){
        URL imagePath = getClass().getResource("Immagini/Board.png");
        BufferedImage result = null;
        try {
            result = ImageIO.read(imagePath);
        } catch (IOException e) {
            System.err.println("Errore, immagine non trovata");
        }
        return result;
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Dimension size = getSize();
        g.drawImage(background, 0, 0,size.width, size.height,0, 0, background.getWidth(), background.getHeight(), null);
    }
};

请注意,您无法在匿名类中使用构造函数,但这对于可重用性是不利的。

希望这有点帮助