-1

I am struggling with this for a few hours now. I make 2D games for a week now and came across a problem (probably just me) which drives me crazy! When I insert an image, it doesn't show. When I try to draw a rectangle, it doesn't show. Here is my code:

import javax.swing.JFrame;
import javax.swing.JPanel;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

//import java.awt.Image;
//import javax.swing.ImageIcon;

public class SpaceInvaders {
    // variables
    static Board table;

    public static void main(String[] args) {
        createGui();
    }

    static void createGui(){
         JFrame frame = new JFrame("Spane Invaders UK");
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         frame.getContentPane().setPreferredSize(new Dimension(1000, 600));

         table = new Board();
         frame.add(table);

         frame.pack();
         frame.setVisible(true);
    }

}

class Board extends JPanel{

    //Image tank;

    public Board(){
        //ImageIcon ii = new ImageIcon(this.getClass().getResource("tank.png"));
        //tank = ii.getImage();
    }

    public void painComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        //g2d.drawImage(tank, 10, 10, null);
        g2d.drawRect(50, 50, 10, 10);
    }
}

There is probably a simple solution for it, so simple in fact, that it is impossible to find on Google. Nevertheless, I'm stuck. Why does nothing happen? How can I fix this?

I commented out the 'Image' code because it isn't the problem.

Feel free to edit.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Another User
  • 128
  • 2
  • 13

2 Answers2

3

Unless it's a typo when writing the code here, you have the method name wrong:

public void paintComponent(Graphics g){
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    //g2d.drawImage(tank, 10, 10, null);
    g2d.drawRect(50, 50, 10, 10);
}

Note: As mentioned in another answer, using the @Override annotation you would have noticed this mistake immediately.

Jurgen Camilleri
  • 3,559
  • 20
  • 45
2

It's a typo.

public void painComponent(Graphics g){

Always use the @Override annotation to avoid these mistakes.

aRestless
  • 1,825
  • 2
  • 18
  • 27
  • 1
    @Wolfdog Try to change your methodology so that you can find these dumb errors we all make faster. For example, you could use the [`@Override` annotation](http://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why). Also you should've tried to put a `println("I'm here")` in the "painComponent" then you would've easily diagnosticated that the problem is that the execution never passes through that code. – DSquare Jun 14 '14 at 14:09