Search code examples
javaimageswingpaintcomponent

paintComponent code not working


I am new to Swing and trying to add a background of an image to my JFrame. However my paintComponent method is not working. Could you please give me some suggestions on how to fix my code so the image is painted in the background?

Code is below:

// 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);

}
}

Solution

  • Overriding paintComponent of a JFrame is not useful, override the paintComponent of its content pane instead.

    Extending JFrame is usually also not necessary.

    Finally, it would better to use initialize to load the image (rather than loading it at each paint call) and do stuff on the content panel if you need.

    Putting it all together, see this example :

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