This question already has an answer here:
- How to Draw an BufferedImage to a JPanel 2 answers
I'm trying to write a Mario 3 level 1 clone, and previously, I was able to get it to show up in JFrames when I had the pulling of the sprite in the constructor of Mario itself. However, because I realized that I'll need to link things like the coordinates and state (small, large) to the moving image itself, I decided to tear it up and have a Mario and MarioComponent. I have a MarioComponent class but it doesn't show up.
public class MarioComponent extends JComponent{
private Mario m;
public MarioComponent(){
m = new Mario();
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D) g;
super.paintComponent(g2);
m.draw();
}
public void moveMario(){
m.move();
repaint();
}
public static void main(String[] args){
JFrame f = new JFrame();
f.setSize(868,915);
MarioComponent m = new MarioComponent();
m.setLocation(100,100);
f.add(m);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
}
my Mario class:
public class Mario{
//all numbers multiplied by 2 from OG game
protected MarioState state;
protected int x, y;
BufferedImage sprite;
public Mario(){
this.state = MarioState.SMALL;
this.x = 54;
this.y = 806;
}
public Mario(MarioState s, int x, int y){
this.state = s;
this.x = x;
this.y = y;
}
public void move(){
this.x+=2;
}
public void jump(){
this.y -= 46;
}
public String getCoordinates(){
return "Mario coords: " + this.x + ", " + this.y + ".";
}
public void draw(){
URL spriteAtLoc = getClass().getResource("sprites/Mario/SmallStandFaceRight.bmp");
try{
sprite = ImageIO.read(spriteAtLoc);
} catch(IOException e){
System.out.println("sprite not found");
e.printStackTrace();
}
}
}
When I try to place a MarioComponent on a JFrame, its not there. How can I remedy this?
You need to use the Graphics object,
g
(org2
-- they're the same object) within your paintComponent as the "pen" with which to draw. You don't do this, so there's no way that anything could or should render. Graphics has a method,g.drawImage(...)
that accepts an image as one of its parameters and would be the best way for this to work.Suggestions:
public void draw(Graphics g){
m.draw(g);