Search code examples
javaswingjframepaintpaintcomponent

Paint Component Method not working for JFrame


I'm trying to paint an image on the screen after trying to use JLabel's and am now trying the paintComponent method. I tried inserting breakpoints after seeing no results and the method doesn't get called, and nothing appears. What should I do? Here is my important code-

`

     public void createWindow(){        

            frame.setVisible(true);  
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.pack();
    frame.setSize(xSize, ySize);
            frame.setLocation(0, 0);
            frame.addComponentListener(this);
            //frame.add(im);             

    }

public void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(placeholder, 0, 0, getWidth(), getHeight(), null); g.drawString("Hello", 100, 100); }

Also I'm using a JFrame instead of JPanel or component if that makes a difference.


Solution

  • JFrame does not have a paintComponent method. You should avoid painting directly to a frame and instead use a JPanel and override its paintComponent method

    You should also make use of the @Override annotation, which will raise a compiler exception if the parent class does not have the method you are trying to override...