Abhishek Choudhary
Abhishek Choudhary

Reputation: 8385

swing JPanel paint method is responding but expecting paintComponents to respond while setting background image

I am setting a background image in JPanel with this

JPanel panel = new JPanel(){
            @Override
            public void paint(Graphics g) {
                super.paint(g);
                g.drawImage(ImageHelper.createResizedCopy(image, height, width, false), 0, 0, null);
            }

        };


        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        panel.setPreferredSize(new Dimension(height, width));
        panel.setOpaque(false);
        panel.add(new JLabel("SCIENCE FAIR"));
        panel.setBorder(new RoundedBorder(1,2,new Color(100, 200, 112)));

        return panel;

I was expecting paintComponents method to respond but somehow paintComponents is not responding but paint is doing the job for painting a background image in JPanel. This JPanel is the child of another JPanel . The Parent JPanel is using MigLayout and inside the parent JPanel, I am adding 4 different JPanels with different different background image.

Background image is done but on top of Background image , I am not able to add JLabel, so I doubt the paint method is the issue

Upvotes: 0

Views: 162

Answers (2)

Andrew Thompson
Andrew Thompson

Reputation: 168815

Also change this:

g.drawImage(ImageHelper.createResizedCopy(image, height, width, false), 0, 0, null);

To this:

g.drawImage(ImageHelper.createResizedCopy(image, height, width, false), 0, 0, this);

A JPanel is an ImageObserver, so you might as well supply it as the .. ImageObserver.

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81674

You're painting the entire component after the children are painted -- you're painting right over them, in other words. Never override paint() in a Swing component; override paintComponent() instead, and be sure to call super.paintComponent() after painting the background image.

Upvotes: 2

Related Questions