0

Right, i am working on a new 2d/top down Java game. Recently, i have been teaching myself how to code in Java however i do have one problem... I have a box in my window which i am able to move around with the W,A,S AND D keys. All i want to know is how to replace that black box with an image(then later worry about animations). Here is my code (btw, this code is also the game engine). Also here is the image that i am trying to add Player image

If anyone can help me it would be much appreciated. Thanks.

Game.java

import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.*;

public class Game {

private final JFrame window = new JFrame();
private final ScreenFactory screenFactory;
private final GameThread gameThread;
private final KeyboardListener keyboardListener;
private final MousepadListener mousepadListener;

public Game(int windowX, int windowY, String title){
    window.setSize(windowX, windowY);
    window.setResizable(false);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setFocusable(true);
    window.setLocationRelativeTo(null);
    window.setTitle("2D Game");
    window.setVisible(true);
    screenFactory = new ScreenFactory(this);
    gameThread = new GameThread(this);
    keyboardListener = new KeyboardListener();
    mousepadListener = new MousepadListener();


    window.add(gameThread);
    window.addKeyListener(keyboardListener);
    window.addMouseListener(mousepadListener);

    new Thread(gameThread).start();

}

public MousepadListener getMousepadListener(){
    return mousepadListener;
}

public KeyboardListener getKeyboardListener(){
    return keyboardListener;
}


public ScreenFactory getScreenFactory(){
    return screenFactory;
}


public JFrame getWindow(){
    return window;
}

}

GameThread.java

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JPanel;

public class GameThread extends JPanel implements Runnable{

private final Game game;

public GameThread(Game game){
    this.game = game;
    setFocusable(true);
}

public void run() {
    while (true){
        try {
            if(game.getScreenFactory().getCurrentScreen() !=null)
                game.getScreenFactory().getCurrentScreen().onUpdate();
            Thread.sleep(10);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

public void paint (Graphics g){
    super.paint(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    if(game.getScreenFactory().getCurrentScreen() !=null)
        game.getScreenFactory().getCurrentScreen() .onDraw(g2d);
    repaint();
}

}

Screen.java

import java.awt.Graphics2D;

public abstract class Screen {

private final ScreenFactory screenFactory;

public Screen(ScreenFactory screenFactory ){
    this.screenFactory = screenFactory;
}

public abstract void onCreate();

public abstract void onUpdate();

public abstract void onDraw(Graphics2D g2d);

public ScreenFactory getScreenFactory(){
    return screenFactory;
}

}

ScreenFactory.java

public class ScreenFactory {

private final Game game;
private Screen screen;

public ScreenFactory(Game game){
    this.game = game;
}

public void showScreen(Screen screen){
    this.screen = screen;
    this.screen.onCreate(); 
}

public Screen getCurrentScreen(){
    return screen;
}

public Game getGame(){
    return game;
}

}

KeyboardListener

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class KeyboardListener implements KeyListener {

private boolean[]keys = new boolean[256];

@Override
public void keyPressed(KeyEvent event) {
    keys[event.getKeyCode()] = true;
}

@Override
public void keyReleased(KeyEvent event) {
    keys[event.getKeyCode()] = false;
}

@Override
public void keyTyped(KeyEvent event) {

}

public boolean isKeyPressed(int key){
    return keys[key];
}

public boolean isKeyReleased(int key){
    return !keys[key];
}

}

MousepadListener.java

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

public class MousepadListener implements MouseListener{

private int mouseX, mouseY;
private boolean clicked;

@Override
public void mouseClicked(MouseEvent event) {
    mouseX = event.getX();
    mouseY = event.getY();
    clicked = true;
}

@Override
public void mouseEntered(MouseEvent event) {

}

@Override
public void mouseExited(MouseEvent event) {

}

@Override
public void mousePressed(MouseEvent event) {
    mouseClicked(event);
    clicked = true;
}

@Override
public void mouseReleased(MouseEvent event) {
    clicked = false;
}

public boolean isMousePressed(){
    return clicked;
}

public int getX(){
    return mouseX; 
}

public int getY(){
    return mouseY;
}

}

TheGame

public class TheGame {

private Game game;

public TheGame(){
    game = new Game(1280, 720, "2D Game");
          game.getScreenFactory()
.showScreenMy(newScreen(game.getScreenFactory()));
}

public static void main(String[] args){ 
    new TheGame();
}
}

MyScreen

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;

public class MyScreen extends Screen{

private int x = 0, y = 0;

public MyScreen(ScreenFactory screenFactory){
    super(screenFactory);
}

@Override
public void onCreate() {
    System.out.println("Creating!...");
}

@Override
public void onUpdate() {
if (getScreenFactory()
.getGame().getKeyboardListener().isKeyPressed(KeyEvent.VK_A))   
    x -= 2;

if (getScreenFactory()
.getGame().getKeyboardListener().isKeyPressed(KeyEvent.VK_D))   
    x += 2;

if (getScreenFactory()
.getGame().getKeyboardListener().isKeyPressed(KeyEvent.VK_W))   
    y -= 2;

if    (getScreenFactory()
.getGame().getKeyboardListener().isKeyPressed(KeyEvent.VK_S))   
    y += 2;

if (y >= 720 - 72)
    y = 720 - 72;
if (y <= 0)
    y = 0;
if (x >= 1280 - 72)
    x = 1280 - 72;
if (x <= 0)
    x = 0;

}

@Override
public void onDraw(Graphics2D g2d) {
    g2d.setColor(Color.black);
    g2d.fillRect(x, y, 72, 72);
}
}

2 Answers2

2

At first read your image as a BufferedImage. And then draw it by drawImage method. Try this:

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;

public class MyScreen extends Screen {

    private int x = 0, y = 0;

    private BufferedImage image;

    public MyScreen(ScreenFactory screenFactory) {
        super(screenFactory);

        try {
            image = ImageIO.read(getClass().getResource("imagepath"));
        } catch (IOException e) {
            // TODO: handle exception
        }

    }

    @Override
    public void onCreate() {
        System.out.println("Creating!...");
    }

    @Override
    public void onUpdate() {
        if (getScreenFactory().getGame().getKeyboardListener().isKeyPressed(KeyEvent.VK_A))
            x -= 2;

        if (getScreenFactory().getGame().getKeyboardListener().isKeyPressed(KeyEvent.VK_D))
            x += 2;

        if (getScreenFactory().getGame().getKeyboardListener().isKeyPressed(KeyEvent.VK_W))
            y -= 2;

        if (getScreenFactory().getGame().getKeyboardListener().isKeyPressed(KeyEvent.VK_S))
            y += 2;

        if (y >= 720 - 72)
            y = 720 - 72;
        if (y <= 0)
            y = 0;
        if (x >= 1280 - 72)
            x = 1280 - 72;
        if (x <= 0)
            x = 0;

    }

    @Override
    public void onDraw(Graphics2D g2d) {
        g2d.setColor(Color.black);
        g2d.fillRect(x, y, 72, 72);
        g2d.drawImage(image, x, y, null);
    }
}
Joseph K.
  • 784
  • 1
  • 9
  • 19
  • hmm... for some reason under ImageIO.read(getClass().getResource("imagepath")); i get a red line saying Unhandled exception type IOException. –  Apr 06 '16 at 21:11
  • You can move the assigning part to the constructor and surround it with try catch block – Joseph K. Apr 06 '16 at 21:12
  • It fixed the IOException however now i get new errors https://gyazo.com/e3a9fa84a97419c3bcf35abe28887390 –  Apr 06 '16 at 21:21
  • Please try this for reading image: `image = ImageIO.read(new FileInputStream("imagepath"));` – Joseph K. Apr 06 '16 at 21:23
  • 1
    wow! Thank you soo much man. All i need to do is find out how to make it move with the KeyboardListener but i will try and find out my self without bothering you too much. Agian...Thank you. –  Apr 06 '16 at 21:29
  • fixed it! All i had to do is add x and y to the draw image like this g2d.drawImage(image,x, y, 72, 72, null); –  Apr 06 '16 at 21:50
0

In your MyScreen class you have the following lines in your onDraw method:

g2d.setColor(Color.black);
g2d.fillRect(x, y, 72, 72);

g2d is a 2DGraphics object used to draw objects on the screen. In the line above, you're creating a black rectangle of equal side lengths (a square).

If you want to instead create an image, simply replace those two lines with the following:

g2d.drawImage(Image img, int x, int y, ImageObserver observer);

Image img is the Image object that you'd like to paint. The image itself must be 72 by 72 pixels to remain the same size as the original black square.

  • To import the image you want, use new ImageIcon("path/to/img.png").getImage()

int x and int y are simply the coordinates of the destination.

ImageObserver observer is too in-depth for your purposes. You can set this to null. You can read more about it here.

All of this information I got from Oracle's documentation. Give their documentation a search next time before asking, you'll find that just about anything you're having trouble with is extensively covered! Also, this question has been asked numerous times, so googling stackoverflow paint image java should give you some quick answers.

Community
  • 1
  • 1
Zulfe
  • 820
  • 7
  • 25