简体   繁体   English

尽管JPanel的setPreferredSize仍未调用PaintComponent()

[英]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. 我知道没有布局或组件的大小为0时,不会调用paint组件方法。

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();
            }
        });
    }
}

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 paintComponent负责绘制组件的“底部”层, paintComponents负责绘制子级

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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