I don't understand why g.drawImage
doesn't draw anything?
public class Board extends JPanel{
Map map;
public Board()
{
map = new Map();
map.loadMap();
}
@Override
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(map.getGround(), 0, 0, this);
g.drawImage(map.getWall(), 100, 100, this);
}
}
Map.loadMap() loads images Ground and Wall from file, functions getGround and getWall return these images. But if i move those 2 lines:
map = new Map();
map.loadMap();
into print function, then it works.
This code works:
public class Board extends JPanel{
Map map;
public Board(){}
@Override
public void paint(Graphics g)
{
map = new Map();
map.loadMap();
super.paint(g);
g.drawImage(map.getGround(), 0, 0, this);
g.drawImage(map.getWall(), 100, 100, this);
}
}
My map class:
public class Map {
Scanner scanner;
int mapHeight = 5, mapWidth = 7;
String[] map = new String[mapHeight];
BufferedImage ground, wall;
public Map(){
loadMap();
loadGround();
loadWall();
}
private void loadMap()
{
try{
scanner = new Scanner(new FileInputStream("/home/bobalice/Map.txt"));
for(int i = 0; i < mapHeight; i++)
{
map[i] = scanner.nextLine();
}
}catch(IOException e){
System.err.println("Error: Map file doesn't exist!");
}finally{
if(scanner != null) scanner.close();
}
}
private void loadGround()
{
try{
ground = ImageIO.read(new File("/home/bobalice/ground.png"));
}catch(IOException e){
System.err.println("Error: ground.png doesn't exist!");
}
}
///
private void loadWall()
{
try{
wall = ImageIO.read(new File("/home/bobalice/wall.png"));
}catch(IOException e){
System.err.println("Error: wall.png doesn't exist!");
}
}
public String[] getMap()
{
return map;
}
public BufferedImage getGround()
{
return ground;
}
public BufferedImage getWall()
{
return wall;
}