0

I want to draw an image on a JPanel which is displayed on a JFrame. I tested the paint method without the frame and it seemed to work, but as soon as I added the image on the frame it won't get shown. Instead I only see a very small square which displays a small area of the image.

Here's my code so far:

TestFrame class:

public class TestFrame extends JFrame {
    private JFrame frame = new JFrame();
    private JPanel jp = new JPanel();
    
    public MyFrame() {
        frame.setTitle("test");
        frame.setSize(300, 300);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        
        frame.setLayout(new BorderLayout());
        
        jp.setBackground(Color.YELLOW);
        frame.add(jp, BorderLayout.CENTER);
        jp.add(new DrawPanel());
        jp.repaint();
        
        frame.setVisible(true);
    }   
}

DrawPanel class:

public class DrawPanel extends JPanel {
    private BufferedImage img;
    
    public DrawPanel() {
        try {
            img = ImageIO.read(getClass().getResourceAsStream("/resources/heart.jpg"));
        } 
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Override protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(img, 0, 0, null);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
FishyK
  • 121
  • 1
  • 7
  • Ok, apparently changing the DrawPanel class to DrawPanel extends JComponent makes it show up infront of the panel – FishyK Apr 30 '22 at 12:09
  • AFAIU this code would not compile, let alone fail at run-time. For better help sooner, [edit] to add a [mre]. For an image, either generate one in code or hotlink to images as seen in [this answer](https://stackoverflow.com/a/19209651/418556). – Andrew Thompson May 20 '22 at 04:04

1 Answers1

-1

Try with this in the method paintComponent():

g.drawimage(img.getImage(), 0, 0, null); 
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 09 '22 at 00:35