0

I am trying to code a board game in Java. I have the board which is an image and the pawns which are shapes (for example a rectangle). I want the board to be the background in the JFrame and the pawns to be over the board. I have tried multiple times but either the board covers the shape or only the shape appears. I could join the shape with the image..and create a new image but this is not what i want. Any ideas?

public class Board extends JPanel {
    @Override
    public void paintComponent(Graphics g) {
     try {
      BufferedImage img = ImageIO.read(new File("C:\\Users\\i\\Desktop\\j.png"));
      Graphics2D g2 = (Graphics2D) g;
      super.paintComponent(g);
      g.drawImage(img, 0, 0, null);
     }catch (IOException ex) {
           Logger.getLogger(Board.class.getName()).log(Level.SEVERE, null, ex);
     }
    }
}

And my other class

public class GameGUI extends javax.swing.JFrame {

    public GameGUI() {
        Board b=new Board();
        setContentPane(b);
        setSize(600,600);
        setTitle("gui");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
                       }
     }

The class for the player

public class Player extends JPanel{
int xPos = 100, yPos = 100, vwidth = 100, vheight = 100;
Rectangle r = new Rectangle(xPos, yPos, vwidth, vheight);
public Player(){ .....}

@Override
    public void paintComponent(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        super.paintComponent(g);
        g.setColor(Color.black);
         if (fill) {
            g.fillRect((int) r.getX(), (int) r.getY(), (int) r.getWidth(), (int) r.getHeight());
         }
         g2.draw(r);
}
}
IS4
  • 11,945
  • 2
  • 47
  • 86
  • 2
    Don't create a new image inside `paintComponent`. Store it as a field and use the reference. – user1803551 Oct 25 '14 at 22:23
  • You are not doing anything with `Player`, how do you want it to show the rectangle? – user1803551 Oct 25 '14 at 22:25
  • 2
    1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example). 2) One way to get images for an example, is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). 3) Use a logical and consistent form of indenting code lines and blocks. The indentation is intended to make the flow of the code easier to follow! – Andrew Thompson Oct 25 '14 at 22:26

0 Answers0