I have a class called Tile, the constructor takes an integer that represents the tile's type. You can load a tileset ( via loadTileset() ) which initalizes the fields -

  • tileset
  • numOfTiles
  • tileWidth
  • tileHeight

My question is, in the constructor, depending on the type variable. How do I figure out the proper x and y cooridates to uses in the getSubimage() method.

enter image description here

So for example, if type is set to the value 2, I'd want to get the x and y position of the upper-left corner of number two.

import java.awt.image.*;
import java.awt.*;
import java.io.*;
import javax.imageio.ImageIO;

public class Tile {

private int type;
private BufferedImage tile;

// tileset attributes
public static BufferedImage tileset;
public static int numOfTiles;

public static int tileWidth;
public static int tileHeight;

// constructor
public Tile(int type) {

    // contruct tile
    this.type = type;
    // ...
    tile = tileset.getSubimage(0, 0, tileWidth, tileHeight);

public static void loadTileset(String filename, Dimension tileSize) {

    // load tileset
    try {
        tileset = ImageIO.read(new File(filename));
    catch(Exception e) {

    // initalize attributes
    tileWidth  = (int) tileSize.getWidth ();
    tileHeight = (int) tileSize.getHeight();

    numOfTiles = (tileset.getWidth() / tileWidth) * (tileset.getHeight() / tileHeight);

How about

int x = type % 3;
int y = type / 3;
| improve this answer | |
  • \$\begingroup\$ the formula for finding the width is perfect, the other is not working properly with different sized maps. \$\endgroup\$ – Trowen Nagbe Feb 18 '14 at 6:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.