zcahfg2
zcahfg2

Reputation: 881

PaintComponent() not called despite setPreferredSize of JPanel

I am trying to understand why the following short piece code does not work. I understand that when there are no Layout or the size of the component is 0, the paint component method isn't called.

But this isn't the case here.

Can you explain why I can't set the background for this?

public class Login extends JPanel {

    private BufferedImage bgImage;

    public Login() {
        super();
        initImages();
        setLayout(new BorderLayout());

        setPreferredSize(new Dimension(600, 600));
        add(new JLabel("Hi"), BorderLayout.CENTER);
    }

    private void initImages() {
        try {
            bgImage = ImageIO.read(new File("images/login.jpg"));
            System.out.println("image loaded");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("image not loaded");
        }
    }

    @Override
    public void paintComponents(Graphics g) {
        super.paintComponents(g);
        g.drawImage(bgImage, 0, 0, null);
        System.out.println("repaint");
    }

    public static void createAndShowGui() {
        JFrame frame = new JFrame();
        Login login = new Login();
        frame.add(login, BorderLayout.CENTER);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

Upvotes: 0

Views: 164

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347204

If you want this to work, then you will need to change...

@Override
public void paintComponents(Graphics g) {
    super.paintComponents(g);
    g.drawImage(bgImage, 0, 0, null);
    System.out.println("repaint");
}

to something more like...

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(bgImage, 0, 0, this);
}

paintComponent is responsible for painting the "bottom" layer of the component, paintComponents is responsible for painting the children

Upvotes: 1

Related Questions