0

I have a board game (think Monopoly) where multiple game pieces can be located on a single tile. I want to be able to arbitrarily place game pieces on the any given tile. I want the tile to have a background (image or just flat color) and be able to place up to 4 game pieces on the tile in a grid. I am currently using this code but the circles do not display.

tank.png is a 135 x 135 pixel background.

GraphicsTile:

public class GraphicsTile extends JPanel {
    public static final Dimension SIZE = new Dimension(135, 135);
    public static final GridLayout MGR = new GridLayout(4, 4);

    public GraphicsTile() {
        super();
        setLayout(MGR);
        initGraphics();
        setSize(SIZE);

        add(new CirclePanel());
    }

    private void initGraphics() {
        JLabel panel = null;
        try {
            Image image = ImageIO.read(new File("tank.png"));

            panel = new JLabel(new ImageIcon(image));
            panel.setSize(SIZE);

        } catch (IOException e) {
            e.printStackTrace();
        }

        add(panel);
    }
}

CirclePanel:

public class CirclePanel extends JPanel {
    public CirclePanel() {
        setSize(33, 33);
    }
    @Override
    protected void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.RED);
        Ellipse2D.Float circle = new Ellipse2D.Float(50, 50, 0, 0);
        g2d.draw(circle);
        g2d.fill(circle);
    }
}
QuyNguyen2013
  • 43
  • 1
  • 10

1 Answers1

1
public class GraphicsTile {

I don't know how your code compiles since your GraphicsTile doesn't extend any Swing component yet you use methods like setLayout(...) and setSize(...) which implies you are trying to use it like a JPanel.

You should not be using setSize(...). A Swing component should have a preferred size. Then the layout manager will set the size and location of the component based on the rules of the layout manager. I'm guessing you have a problem because the preferred size is (0, 0).

I also have no idea how you add the GraphicsTile to the parent component. Again it looks like you are using setSize() when you should let the layout manager position the tiles on the game board.

Also, if you want to have a background image with circles on top then you need a hierarchical structure. That is you need something like:

  • panel
    • background image
      • circle component.

So my suggestions are:

  1. CirclePanel needs to implement the getPreferredSize(...) method to return the size of your custom painting.

  2. Your GraphicsTile class needs to extend JPanel. You would then override the paintComponent(...) method to draw your background image. Now you can add the CirclePanel instances to the this panel which will use the GridLayout.

camickr
  • 321,443
  • 19
  • 166
  • 288