user2208056
user2208056

Reputation: 23

paintComponent on JPanel not working

I've spent almost 2 hours now on it but I can't get it working. I just want to paint a image on a JPanel.

I want to paint the imageChaser image on the arena JPanel. But it's not displaying. What am i doing wrong?

Heres my code :

public class GuiGameBoard extends JPanel {

//import stuff


private JPanel arena;

BufferedImage imageChaser;
BufferedImage imageChaserSelected;
BufferedImage imageTarget;

public GuiGameBoard() {

    this.setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    arena = new JPanel();
    arena.setPreferredSize(new Dimension(500, 500));
    arena.setBackground(Color.BLACK);


    this.add(arena);

    try 
    {
        File inputChaser = new File("resources\\chaser.png");
        imageChaser = ImageIO.read(inputChaser);

        File inputChaserSelected = new File("resources\\chaser_selected.png");
        imageChaserSelected = ImageIO.read(inputChaserSelected);

        File inputTarget = new File("resources\\target.png");
        imageTarget = ImageIO.read(inputTarget);

    } 
    catch (IOException ie) 
    {
        System.out.println("Error:"+ie.getMessage());
    }

}

public void paintComponent(Graphics g){

    super.paintComponent(g);
    g.drawImage(imageChaser, 0, 0, null);
}

}

Upvotes: 1

Views: 229

Answers (2)

PrR3
PrR3

Reputation: 1246

I think the problem is, that your hiding your picture by adding the JPanel arena to your GuiGameBoard class, which already is a JPanel.

But without an SSCCE, giving an adequate answer isn't possible...

Upvotes: 3

Punyapat
Punyapat

Reputation: 399

I think you forget a 'top-level container' e.g. JFrame.

Take a look at this example example code.

For more information click here

Upvotes: 1

Related Questions