Hello all i have two questions about a game template that i quickly wrote up… I am used to writing applets but i need to make a standalone game this time.
1- How do i load an image? “getImage(getCodeBase(), “res/image.png”);” Isn’t working…
2- How do you use a keyListener. The usual way for applets isn’t working.
Help much appreciated
Here is the code:
package com.ion.rpgnoname;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable, KeyListener{
private static final long serialVersionUID = 1L;
private static final int SCALE = 4;
static int WIDTH = 125;
static int HEIGHT = 125;
static String NAME = "GAME UNNAMED" ;
Image guy;
int x = 0;
int y = 0;
Image dbImage;
Graphics dbg;
public void init () {
setSize (WIDTH, HEIGHT);
setFocusable(true);
setBackground(Color.BLACK);
addKeyListener(this);
guy = getImage(getCodeBase(), "res/image.png");
}
public void start() {
Thread th = new Thread(this);
th.start();
}
public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
while(true){
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
}
}
public void paint(Graphics g) {
g.setColor(Color.BLACK);
g.fillOval(x, y, 12, 12);
g.drawImage(guy, 40, 40, this);
}
public void update(Graphics g){
if (dbImage == null)
{
dbImage = createImage (this.getSize().width, this.getSize().height);
dbg = dbImage.getGraphics ();
}
dbg.setColor (getBackground ());
dbg.fillRect (0, 0, this.getSize().width, this.getSize().height);
dbg.setColor (getForeground());
paint (dbg);
g.drawImage (dbImage, 0, 0, this);
}
public static void main(String[] args){
Game game = new Game();
game.setMinimumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
game.setMaximumSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
game.setPreferredSize(new Dimension(WIDTH*SCALE, HEIGHT*SCALE));
JFrame frame = new JFrame(Game.NAME);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(game);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE){
x++;
y++;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}