簡體   English   中英

盡管JPanel的setPreferredSize仍未調用PaintComponent()

[英]PaintComponent() not called despite setPreferredSize of JPanel

我試圖理解為什么下面的短代碼不起作用。 我知道沒有布局或組件的大小為0時,不會調用paint組件方法。

但是這里不是這種情況。

您能解釋為什么我不能為此設置背景嗎?

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

如果您想讓它正常工作,則需要進行更改...

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

更像...

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

paintComponent負責繪制組件的“底部”層, paintComponents負責繪制子級

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM