0

I'm trying to create a simple Card class that extends BufferedImage so I can draw the card directly on the screen. But the card has two faces. The front, and the back. I am including a flip(boolean faceup) method that I want to change the image from one side to the next, but it seems that since the Class extends BufferedImage, it's final? I'm not sure, that's my impression. It doesn't change from the original image drawn in the constructor. Is there any way around this so I can still paint the card directly on-screen? This is what I have so far...

  public Card(int rank, int suit)
  {
     super(50,70,TYPE_INT_ARGB);
     this.rank = rank;
     this.suit = suit;
     try{bi = ImageIO.read(getClass().getResource(toString()+".png"));
     back = ImageIO.read(getClass().getResource("back.png"));}
     catch(IOException e){e.printStackTrace();}
     Graphics2D g = createGraphics();
     g.drawImage(back,0,0,null);
     g.dispose();
  }

  public void flip(boolean faceup)
  {
     this.faceup = faceup;
     Graphics2D g = createGraphics();
     if(faceup)g.drawImage(bi,0,0,null);
     else g.drawImage(back,0,0,null);
     g.dispose();
  }
user3376587
  • 134
  • 2
  • 12
  • While I wouldn't generally recommend extending `BufferedImage` (do as @camickr says, create a `Card` class with two images), I do think your approach could work. Just keep in mind that `BufferedImage`s don't repaint themselves when they change. You have to issue a `repaint()` (assuming a Swing app) after calling `flip()`. – Harald K Sep 28 '15 at 07:54

1 Answers1

3

Don't extend BufferedImage.

Instead your class can contain two BufferedImages:

  1. the front
  2. the back

Then the painting method will paint the front or the back depending on the "flip" property.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • I know I could do that, but I want to be able to easily draw the image anywhere on screen. If it were a component, doing so would be a bit more difficult for me. Unless you suggest a getImage() method? I'd still like to figure out a way to make a two-sided bufferedimage. – user3376587 Sep 26 '15 at 17:14
  • You can access the pixel value in a BufferedImage, by using the getRaster().getSample(x,y,c), or even faster by the DataBuffer. – FiReTiTi Sep 26 '15 at 20:08
  • `but I want to be able to easily draw the image anywhere on screen.` that is what the x/y values are for in the drawImage() method. – camickr Sep 26 '15 at 21:41