简体   繁体   中英

Java repaint() doesn't call paintComponent() for drawing image

I have read a lot of answers about this problem but I can't manage to find my error even on a simple code. Here is the problem : I'd like to draw an Image in a JLabel which is in a JPanel, but the paintComponent() method of the JLabel isn't called.

Here is the code :

The ImagePainter class should draw an image

public class ImagePainter extends JLabel{
    private Image image;

    public ImagePainter(){
        try {
            image = ImageIO.read(new File("src/testgui/image.png"));
        } catch (IOException exception) {
            exception.printStackTrace();
        }
    }

    @Override
    protected void paintComponent(Graphics g){
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
        System.out.println("in paintComponent");
    }
}

Here is a standard JFrame. I took care to add the JPanel to the contentPane

public class Display extends JFrame{

    public Display(){
        JPanel jp = new JPanel();
        ImagePainter i = new ImagePainter();

        getContentPane().add(jp);
        jp.add(i);
        jp.repaint();

        setSize(800, 800);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}

And finally the main. I instanciate Display on the EDT like everyone tell to do :

public class Main {

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable(){
            @Override
            public void run(){
                Display d = new Display();
            }
        });
    }

}

Finally, I observed that if I directly add the ImagePainter to the contentPane, the image is drawn correctly. It's probably a stupid error but I spend literally hours trying to find it and really can't see it. Thank you in advance !

The label does not account for the preferred size of the image when the image is custom painted! The panel by default has a flow layout. A flow layout does not stretch components to fit. So that label would have size of 0 x 0 pixels. You can confirm that by adding a visible border to the label.

But given the image is displayed in a label, why not just set the image as the icon of the label?

同样,Display构造函数中的jp.repaint()语句也没有用,因为您尚未将框架设置为可见。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM