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