paintComponent 代码不起作用

paintComponent code not working

我是 Swing 的新手,正在尝试将图像背景添加到我的 JFrame。但是我的 paintComponent 方法不起作用。你能给我一些关于如何修复我的代码以便在背景中绘制图像的建议吗?

代码如下:

// all necessary imports have been added.
public class Menu extends JFrame  {
private Image backgroundImage;
private JFrame frame;

public static void main(String[] args) throws IOException {
    Menu window = new Menu();
    window.frame.setVisible(true);
}

public Menu() throws IOException {
    initialize();
}

public void initialize() throws IOException {

    frame = new JFrame();
    frame.setBounds(100, 100, 312, 294);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().setLayout(null);

}
public void paintComponent(Graphics g) throws IOException {
    backgroundImage = ImageIO.read(new File("P:\Profiles\workspace\Games\Images\matrix.jpg"));
    g.drawImage(backgroundImage, 0, 0, null);

}
}

覆盖 JFramepaintComponent 没有用,而是覆盖其内容窗格的 paintComponent

通常也不需要延长 JFrame

最后,最好使用 initialize 加载图像(而不是在每次绘制调用时加载它)并在需要时在内容面板上做一些事情。

把它们放在一起,看这个例子:

public class Menu extends JPanel {

    private Image backgroundImage;

    public static void main(final String[] args) throws IOException {
        Menu menu = new Menu();
        JFrame frame = new JFrame();
        frame.setContentPane(menu);
        frame.setBounds(100, 100, 312, 294);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public Menu() throws IOException {
        initialize();
    }

    public void initialize() throws IOException {

        backgroundImage = ImageIO.read(new File("P:\Profiles\workspace\Games\Images\matrix.jpg"));

    }

    @Override
    public void paintComponent(final Graphics g){

        super.paintComponent(g);
        g.drawImage(backgroundImage, 0, 0, this);

    }

}