I have been running Eclipse Indigo for a few months now, and I have run into a bug that I cannot seem to find an answer to. I am creating a small 2d side-scroller game similar to that of mario, the old zelda, etc.
I was going to show a my dad what new feature I had added into my program. Instead of coming upstairs to see my program on my computer, my dad decided that he could get into it using a sudo screen-viewing thing that I am not sure of. We have used this before, and basically all it does is let you see the screen of another computer in your home (on the same IP interface), and you can use the computer too.
I didn't want to show my program to my dad this way, so I told him to come upstairs. He did, and ever since then, eclipse will not show any graphics inside of your JFrame in your program. It will show things such as words (written on the screen), but will not show ANY graphics. Such as your background image, or your character, or anything else. I am POSITIVE that it isn't some problem with my coding, because I had tested and played the game quite a few times before my dad did the screen-viewing thing (we are both on linux mint 12, BTW).
I think that this bug is related to the screen-viewing thing.
I would love it if I could get some help. any would be great. Thanks.
-This has been solved*
Board
package External;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Board extends JPanel implements ActionListener, Runnable {
Dude p;
Image img;
Timer time;
int v = 172;
Thread animator;
boolean a = false;
boolean done2 = false;
public Board() {
p = new Dude();
addKeyListener(new AL());
setFocusable(true);
ImageIcon i = new ImageIcon ("/home/clark/Desktop/Swindle_test_background.png");
img = i.getImage();
time = new Timer (3, this);
time.start();
}
public void actionPerformed(ActionEvent e) {
p.move();
repaint();
}
public void paint(Graphics g) {
if (p.dy == 1 && done2 == false)
{
done2 = true;
animator = new Thread(this);
animator.start();
}
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
if ((p.getX() - 590) % 2400 == 0)
p.nx = 0;
if ((p.getX() - 1790) % 2400 == 0)
p.nx2 = 0;
g2d.drawImage(img, 985-p.nx2, 0, null);
if (p.getX() >= 921)
g2d.drawImage(img, 985-p.nx, 0, null);
g2d.drawImage(p.getImage(), 75, v, null);
}
private class AL extends KeyAdapter {
public void keyReleased(KeyEvent e) {
p.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
p.keyPressed(e);
}
}
boolean h = false;
boolean done = false;
public void cycle() {
if (h == false)
v--;
if (v == 125)
h = true;
if (h == true && v <= 172 ) {
v++;
if (v == 172) {
done = true;
}
}
}
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (done == false) {
cycle();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = 10 - timeDiff;
if (sleep < 0)
sleep = 2;
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
done = false;
h = false;
done2 = false;
}
}
Dude
package External;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Dude {
int x, dx, y, nx2, nx, dy;
Image Swindle_Man_Right;
ImageIcon r = new ImageIcon("/home/clark/Desktop/Swindle_Man_Right.png");
ImageIcon l = new ImageIcon("/home/clark/Desktop/Swindle_Man_Left.png");
ImageIcon j = new ImageIcon("/home/clark/Desktop/Swindle_Man_Jump.png");
public Dude() {
Swindle_Man_Right = l.getImage();
x = 75;
nx2 = 685;
nx = 0;
y = 172;
}
public void move() {
x = x + dx;
nx2 = nx2 + dx;
nx = nx + dx;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return Swindle_Man_Right;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
{ dx = -1;
Swindle_Man_Right = l.getImage();
}
if (key == KeyEvent.VK_RIGHT)
{dx = 1;
Swindle_Man_Right = r.getImage();
}
if (key == KeyEvent.VK_UP)
{dy = 1;
Swindle_Man_Right= j.getImage();
} }
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
dx = 0;
if (key == KeyEvent.VK_RIGHT)
dx = 0;
if (key == KeyEvent.VK_UP)
{dy = 0;
Swindle_Man_Right= r.getImage();}
}
}
Frame
package External;
import javax.swing.*;
public class Frame {
public Frame() {
JFrame frame = new JFrame("Swindle [version 0.1.9]");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,390);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
new Frame();
}
}
As near as I can tell, you've not added anything to the frame.
After I replaced the graphics with my own, I was able to get it running...
public class Frame {
public static void main(String[] args) {
new Frame();
}
public Frame() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Swindle [version 0.1.9]");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// This is kind of important...
frame.add(new Board());
frame.setSize(700, 390);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
While I've only given the code quick glance, I would recommend that you don't use ImageIcon to load you images and instead use the ImageIO API. Apart from supporting more image formats, it will throw more errors when it can't load the images.
I would also avoid using KeyListener in favor of key bindings. They don't suffer from the same focus issues as KeyListener
Related
I am making a game and the game window will only open to the size of the title. Please let me know what changes I need to make the "b.setSize(900,885)" work. I will change or add any amount of code if needed.
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class Background extends JFrame implements KeyListener, ActionListener{
int platform1X = 300, platform1Y = 555, platform2X, platform2Y;
Image image;
public boolean isJumping = false;
int playerx = 100, playery = 585, velX = 0, velY = 0;
public boolean[] keyDown = new boolean[4];
private int fallingSpeed = 0;
private int gravity = 5;
private int jumpPower = -30;
public Background(){
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
keyDown[0] = false;
keyDown[1] = false;
keyDown[2] = false;
keyDown[3] = false;
}
public void paint(Graphics g){
if(!isOnGround()){
fall();
}
ImageIcon i = new ImageIcon("/Users/kairotieremorton/Documents/java code/Kairo and Enoch Game/src/images/Backgroundsquareman.png");
image = i.getImage();
g.drawImage(image, 0, 0, 900, 700, null);
g.setColor(Color.BLUE);
g.fillRect(platform1X, platform1Y, 120, 20);
g.setColor(Color.RED);
g.fillRect(playerx, playery, 30, 30);
try {
Thread.sleep(40);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
playery = playery + velY;
playerx = playerx + velX;
}
public static void main(String[] args){
Background b = new Background();
b.setTitle("Game");
b.setSize(900,885);
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.setVisible(true);
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(isOnGround() && key == KeyEvent.VK_SPACE){
keyDown[0] = true;
jump();
}
//if(key == KeyEvent.VK_DOWN){ setvelY(5); keyDown[1] = true;}
if(key == KeyEvent.VK_LEFT) { setvelX(-5); keyDown[2] = true;}
if(key == KeyEvent.VK_RIGHT) { setvelX(5); keyDown[3] = true;}
System.out.println(key);
System.out.println(playerx);
System.out.println(playery);
}
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if(key == KeyEvent.VK_SPACE){ keyDown[0] = false;} //tempObject.setVelY(0);
//if(key == KeyEvent.VK_DOWN) keyDown[1] = false;//tempObject.setVelY(0);
if(key == KeyEvent.VK_LEFT) keyDown[2] = false;//tempObject.setVelX(0);
if(key == KeyEvent.VK_RIGHT) keyDown[3] = false; //tempObject.setVelX(0);
//vertical movement
if(!keyDown[0]) setvelY(0); System.out.println(isOnGround());
//horizontal movement
if(!keyDown[2] && !keyDown[3]) setvelX(0);
}
public void keyTyped(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {
//playery = playery + velY;
//playerx = playerx + velX;
//repaint();
}
public boolean isOnGround(){
if(playery + (30 /2) >= 585) {
return true;
}
return false;
}
public void fall(){
playery = playery + fallingSpeed;
fallingSpeed = fallingSpeed + gravity;
}
public void jump(){
fallingSpeed = jumpPower;
fall();
}
public void setvelX(int velX) {
this.velX = velX;
}
public void setvelY(int velY) {
this.velY = velY;
}
public float getvelX(){
return velX;
}
public float getvelY(){
return velY;
}
public int getplayerx(){
return playerx;
}
public int getplayery(){
return playery;
}
public void setplayerx(int playerx) {
this.playerx = playerx;
}
public void setplayery(int playery) {
this.playery = playery;
}
public Rectangle getBounds(){
return new Rectangle(getplatform1X(), platform1Y(), 120, 20);
}
public int getplatform1X(){
return platform1X;
}
public int platform1Y(){
return platform1Y;
}
public Rectangle getBoundsTop(){
return new Rectangle(getplayerx() + 10, getplayery(), 30 - 20, 5);
}
public Rectangle getBoundsBottom(){
return new Rectangle(getplayerx() + 10, getplayery() + 30 - 5, 30 - 20, 5);
}
public Rectangle getBoundsLeft(){
return new Rectangle(getplayerx(), getplayery()+10, 5, 30 -20);
}
public Rectangle getBoundsRigth(){
return new Rectangle(getplayerx() + 30 - 5, getplayery()+10, 5, 30 - 20);
}
}
Okay, that took a lot of looking, but...
public Rectangle getBounds() {
return new Rectangle(getplatform1X(), platform1Y(), 120, 20);
}
is your problem. JFrame#getBounds is a method used by JFrame to return the position and the size of the component and since you've overridden it, it will now ignore any values you pass to setSize (directly or indirectly)
Have a read of the following for reasons why you shouldn't override paint of top level containers like JFrame
How can I set in the midst?
Graphics rendering in title bar
Java JFrame .setSize(x, y) not working?
How to get the EXACT middle of a screen, even when re-sized
As a general rule of thumb, you should avoid extending from JFrame, as you're not really adding any new functionality to the class, it locks you into a single use case and, based on your experience, can cause other problems.
You should start with something like JPanel and override its paintComponent method instead (and make sure you call super.paintComponent before you do any custom painting)
Take a look at Painting in AWT and Swing and Performing Custom Painting
You paint methods should run as fast as possible, so you should avoid loading resources like loading images, within the paint method
Swing is single threaded, so calling Thread.sleep in the paint method will cause the entire program to stop, including it's ability to respond to new events from the user.
I'd also discourage you from using KeyListener, using the key bindings API will be more reliable. Take a look at How to Use Key Bindings for more details
Edit:
A better way to achieve the same result is to call b.setPreferredSize(dimension); and then pack() your frame.
See this answer for more information about JFrame.pack() :
https://stackoverflow.com/a/22982334/5224040
Try this in your main method:
public static void main(String[] args) {
Background b = new Background();
Dimension d = new Dimension(900, 885); //Create a new Dimension
b.setTitle("Game");
b.setPreferredSize(d); //Set the PreferredSize;
b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b.pack(); //Pack the frame
b.setVisible(true); //Setting Visible
}
You can also use the following methods to reposition your frame as necessary:
b.setLocationRelativeTo(null); //center the location on the screen.
b.setLocation(0, 0); //Set location explicitly
Call either of these methods below b.pack(); to reposition your frame.
So I've pretty much thrown together a basic game in java by following a bunch of different tutorials - the problem is i cant manage to figure out how to get my sprite to move in different directions. Here is the code for my main
package com.game.src.main;
import java.awt.Canvas;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import javax.swing.JFrame;
public class Game extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 850;
public static final int HEIGHT = 650;
public static final int SCALE = 1;
public final String TITLE = "Racing Game!";
static ServerSocket serverSocket;
static Socket socket;
static DataOutputStream out;
private boolean running = false;
private Thread thread;
private BufferedImage image = new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_INT_RGB);
private BufferedImage spriteSheet = null;
private BufferedImage spriteSheet2 = null;
private BufferedImage background = null;
private BufferedImage MenuBackground = null;
private Player p;
private Player2 p2;
private Menu menu;
public static enum STATE {
MENU,
GAME
};
public static STATE State = STATE.MENU;
public void init() {
BufferedImageLoader loader = new BufferedImageLoader();
try {
spriteSheet = loader.loadImage("/Sprite_Sheet.png");
background = loader.loadImage("/Track.png");
MenuBackground = loader.loadImage("/MenuBG.fw.png");
}
catch (IOException e) {
e.printStackTrace();
}
menu = new Menu();
addKeyListener(new KeyInput(this));
this.addMouseListener(new MouseInput());
p = new Player(365, 500, this);
p2 = new Player2(365, 550, this);
}
private synchronized void start() {
if(running)
return;
running = true;
thread = new Thread(this);
thread.start();
}
private synchronized void stop() {
if(!running)
return;
running = false;
try {
thread.join();
}
catch (InterruptedException e) {
e.printStackTrace();
}
System.exit(1);
}
public void run() {
init();
long lastTime = System.nanoTime();
final double amountOfTicks = 60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
int updates = 0;
int frames = 0;
long timer = System.currentTimeMillis();
while(running) {
long now = System.nanoTime();
delta += (now - lastTime) / ns;
lastTime = now;
if(delta >= 1) {
tick();
updates++;
delta--;
}
render();
frames++;
if(System.currentTimeMillis() - timer > 1000) {
timer += 1000;
System.out.println(updates + " FPS, TICKS " + frames);
updates = 0;
frames = 0;
}
}
stop();
}
private void tick() {
if(State == STATE.GAME){
p.tick();
p2.tick();
}
}
private void render() {
BufferStrategy bs = this.getBufferStrategy();
if(bs == null) {
createBufferStrategy(3);
return;
}
Graphics g = bs.getDrawGraphics();
g.drawImage(image, 0, 0, getWidth(), getHeight(), this);
g.drawImage(MenuBackground, 0, 0, null);
if(State == STATE.GAME){
//Drawing the main games background
g.drawImage(background, 0, 0, null);
p.render(g);
p2.render(g);
}
else if(State == STATE.MENU){
menu.render(g);
}
g.dispose();
bs.show();
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(State == STATE.GAME){
if(key == KeyEvent.VK_RIGHT){
p.setVelX(5);
}
if(key == KeyEvent.VK_D){
p2.setVelX2(5);
}
else if(key == KeyEvent.VK_LEFT) {
p.setVelX(-5);
}
else if(key == KeyEvent.VK_A) {
p2.setVelX2(-5);
}
else if(key == KeyEvent.VK_DOWN) {
p.setVelY(5);
}
else if(key == KeyEvent.VK_S) {
p2.setVelY2(5);
}
else if(key == KeyEvent.VK_UP) {
p.setVelY(-5);
}
else if(key == KeyEvent.VK_W) {
p2.setVelY2(-5);
}
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_RIGHT){
p.setVelX(0);
}
if(key == KeyEvent.VK_D){
p2.setVelX2(0);
}
else if(key == KeyEvent.VK_LEFT) {
p.setVelX(0);
}
else if(key == KeyEvent.VK_A) {
p2.setVelX2(0);
}
else if(key == KeyEvent.VK_DOWN) {
p.setVelY(0);
}
else if(key == KeyEvent.VK_S) {
p2.setVelY2(0);
}
else if(key == KeyEvent.VK_UP) {
p.setVelY(0);
}
else if(key == KeyEvent.VK_W) {
p2.setVelY2(0);
}
}
public static void main(String args[]) throws Exception {
Game game = new Game();
game.setPreferredSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMaximumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
game.setMinimumSize(new Dimension(WIDTH * SCALE, HEIGHT * SCALE));
JFrame frame = new JFrame(game.TITLE);
frame.add(game);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.start();
System.out.println("Starting server....");
serverSocket = new ServerSocket(7777);
System.out.println("Server started");
socket = serverSocket.accept();
System.out.println("Connecting from: " + socket.getInetAddress());
out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("This is a test of Java Sockets");
System.out.println("Data has been sent");
}
public BufferedImage getSpriteSheet() {
return spriteSheet;
}
public BufferedImage getSpriteSheet2() {
return spriteSheet2;
}
}
This is my player class
package com.game.src.main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public class Player {
private double x;
private double y;
private double velX = 0;
private double velY = 0;
private BufferedImage player;
BufferedImageLoader loader = new BufferedImageLoader();
BufferedImage SpriteSheet = null;
public Player(double x, double y, Game game) {
this.x = x;
this.y = y;
//New instance of Sprite sheet - reading from buffered image loader
SpriteSheet ss = new SpriteSheet(game.getSpriteSheet());
player = ss.grabImage(1, 1, 50, 50);
try {
SpriteSheet = loader.loadImage("/Sprite_Sheet.png");
}
catch(Exception e) {
e.printStackTrace();
}
}
public void tick() {
x+=velX;
y+=velY;
//Adding basic collision
if(x < 0 + 50) {
x = 0 + 50;
}
if(x >= 850 - 100) {
x = 850 - 100;
}
if(y < 0 + 100) {
y = 0 + 100;
}
if(y >= 650 - 100){
y = 650 - 100;
}
}
public void render(Graphics g){
//Draw Track
Color c1 = Color.green;
g.setColor( c1 );
g.fillRect( 150, 200, 550, 300 ); //grass
Color c2 = Color.black;
g.setColor( c2 );
g.drawRect(50, 100, 750, 500); // outer edge
g.drawRect(150, 200, 550, 300); // inner edge
Color c3 = Color.yellow;
g.setColor( c3 );
g.drawRect( 100, 150, 650, 400 ); // mid-lane marker
Color c4 = Color.white;
g.setColor( c4 );
g.drawLine( 425, 500, 425, 600 ); // start line
g.drawImage(player, (int)x, (int)y, null);
}
public double getX(Graphics g){
return x;
}
public double getY(){
return y;
}
public void setX(double x){
this.x = x;
}
public void setY(double y){
this.y = y;
}
public void setVelX(double velX){
this.velX = velX;
}
public void setVelY(double velY){
this.velY = velY;
}
}
I have two players in this game but i'm really stuck on how i can change the sprites direction by 22.5% in a desired direction so if i pressed the up key for player 1 it would rotate my car 22.5% north etc. I have a sprite sheet with 16 sprites for each player for every change in angle by 22.5% This is really confusing me and i'm not sure how i can implement this,
Thanks for taking the time to look
This is a basic example of spinning a sprite
What this is maintain's a virtual state which the Player object inspects in order to determine how it should be changed accordingly. This separates the action from the result, meaning that it would be possible to substitute the action (arrow up key) with some other action, but still obtain the same result.
This example also uses the key bindings API, which doesn't suffer from the same focus related issues that KeyListener does, but this is a pure Swing API and won't be compatiable with Canvas, but is a nice demonstration ;)
The real magic occurs in the characters paint method...
public void paint(Graphics2D g2d) {
Graphics2D g = (Graphics2D) g2d.create();
AffineTransform at = new AffineTransform();
at.translate(x, y);
at.rotate(Math.toRadians(angle), character.getWidth() / 2, character.getHeight() / 2);
g.transform(at);
g.drawImage(character, 0, 0, null);
}
Basically, this creates a AffineTransformation which is then compounded to produce the result we need. That is, first it's anchor position is translated to the characters x/y position and then rotated about the characters center point. Because it's been translated, we can simply paint the character at 0x0. This much easier then try to calculate the characters rotation anchor somewhere else in virtual space - IMHO
The character is rotated by pressing either the Up or Down arrow keys. While pressed, the character will continue to rotate, this is a feature of the example for demonstration purpose.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class RotateCharater {
public static void main(String[] args) {
new RotateCharater();
}
public RotateCharater() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private DefaultState state;
private Player player;
public TestPane() {
player = new Player();
state = new DefaultState();
InputMap im = getInputMap(WHEN_IN_FOCUSED_WINDOW);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "upKeyPressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, true), "upKeyReleased");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "downKeyPressed");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, true), "downKeyReleased");
ActionMap am = getActionMap();
am.put("upKeyPressed", new UpKeyAction(state, true));
am.put("upKeyReleased", new UpKeyAction(state, false));
am.put("downKeyPressed", new DownKeyAction(state, true));
am.put("downKeyReleased", new DownKeyAction(state, false));
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
player.update(state);
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
player.paint(g2d);
g2d.dispose();
}
public class UpKeyAction extends AbstractAction {
private DefaultState state;
private boolean pressed;
public UpKeyAction(DefaultState state, boolean pressed) {
this.state = state;
this.pressed = pressed;
}
#Override
public void actionPerformed(ActionEvent e) {
state.setUpKeyPressed(pressed);
}
}
public class DownKeyAction extends AbstractAction {
private DefaultState state;
private boolean pressed;
public DownKeyAction(DefaultState state, boolean pressed) {
this.state = state;
this.pressed = pressed;
}
#Override
public void actionPerformed(ActionEvent e) {
state.setDownKeyPressed(pressed);
}
}
}
public interface State {
public boolean isUpKeyPressed();
public boolean isDownKeyPressed();
}
public class DefaultState implements State {
private boolean upKeyPressed;
private boolean downKeyPressed;
public boolean isDownKeyPressed() {
return downKeyPressed;
}
public boolean isUpKeyPressed() {
return upKeyPressed;
}
public void setDownKeyPressed(boolean downKeyPressed) {
this.downKeyPressed = downKeyPressed;
upKeyPressed = false;
}
public void setUpKeyPressed(boolean upKeyPressed) {
this.upKeyPressed = upKeyPressed;
downKeyPressed = false;
}
}
public class Player {
private BufferedImage character;
private int x = 100 - 32, y = 100 - 32;
private double angle;
public Player() {
try {
character = ImageIO.read(getClass().getResource("/Character.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void paint(Graphics2D g2d) {
Graphics2D g = (Graphics2D) g2d.create();
AffineTransform at = new AffineTransform();
at.translate(x, y);
at.rotate(Math.toRadians(angle), character.getWidth() / 2, character.getHeight() / 2);
g.transform(at);
g.drawImage(character, 0, 0, null);
}
public void update(State state) {
if (state.isUpKeyPressed()) {
angle -= 22.5;
} else if (state.isDownKeyPressed()) {
angle += 22.5;
}
}
}
}
Remember, this is just an example used to present the concept ;)
i'm trying to create a game. And almost everytime I move, it's leaving a trail
Code:
package lt.mchackers.gametest.main;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import lt.mchackers.gametest.handlers.InputHandler;
/**
* Main class for the game
*/
public class Main extends JFrame
{
private static final long serialVersionUID = -828018325337767157L;
boolean isRunning = true;
int fps = 30;
int windowWidth = 320;
int windowHeight = 320;
int speed;
BufferedImage backBuffer;
Insets insets;
InputHandler input;
int x = 0;
int y = 0;
int xa = 0;
int ya = 0;
Coordinates coords = new Coordinates(0, 0);
public static void main(String[] args)
{ Main game = new Main();
game.run();
System.exit(0);
}
/**
* This method starts the game and runs it in a loop
*/
public void run()
{
initialize();
while(isRunning)
{
long time = System.currentTimeMillis();
update();
draw();
// delay for each frame - time it took for one frame
time = (1000 / fps) - (System.currentTimeMillis() - time);
if (time > 0)
{
try
{
Thread.sleep(time);
}
catch(Exception e){}
}
}
setVisible(false);
}
/**
* This method will set up everything need for the game to run
*/
void initialize()
{
setTitle("Game Tutorial");
setSize(windowWidth, windowHeight);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
insets = getInsets();
setSize(insets.left + windowWidth + insets.right,
insets.top + windowHeight + insets.bottom);
backBuffer = new BufferedImage(windowWidth, windowHeight, BufferedImage.TYPE_INT_RGB);
input = new InputHandler(this);
Graphics bbg = backBuffer.getGraphics();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("map"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = null;
try {
BufferedImage gray = ImageIO.read(new File("gray.png"));
BufferedImage black = ImageIO.read(new File("black.png"));
while ((line = reader.readLine()) != null) {
for(String s : line.split(""))
{
if (s.contains("*"))
{
bbg.drawImage(gray, xa-32, ya, null);
}
else if (s.contains("#"))
{
bbg.drawImage(black, xa-32, ya, null);
}
if (xa < 320)
{
xa += 32;
}
else
{
ya += 32;
xa = 0;
}
System.out.println(xa);
System.out.println(ya);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* This method will check for input, move things
* around and check for win conditions, etc
*/
void update()
{
if (input.isKeyDown(KeyEvent.VK_NUMPAD0))
{
speed -= 1;
}
if (input.isKeyDown(KeyEvent.VK_NUMPAD1))
{
speed += 1;
}
if (input.isKeyDown(KeyEvent.VK_RIGHT))
{
coords.setCoords(coords.getX() + 32, coords.getY());
}
if (input.isKeyDown(KeyEvent.VK_LEFT))
{
coords.setCoords(coords.getX() - 32, coords.getY());
}
if (input.isKeyDown(KeyEvent.VK_UP))
{
coords.setCoords(coords.getX(), coords.getY() - 32);
}
if (input.isKeyDown(KeyEvent.VK_DOWN))
{
coords.setCoords(coords.getX(), coords.getY() + 32);
}
//System.out.println(x);
//System.out.println(y);
//System.out.println(speed);
if (coords.getY() < 0)
{
coords.setCoords(coords.getX(), 0);
}
if (coords.getX() < 0)
{
coords.setCoords(0, coords.getY());
}
if (coords.getX() > windowWidth - 32)
{
coords.setCoords(windowWidth - 32, coords.getY());
}
if (coords.getY() > windowHeight - 32)
{
coords.setCoords(coords.getX(), windowHeight - 32);
// y = windowHeight - 32;
}
}
/**
* This method will draw everything
*/
void draw()
{
Graphics g = getGraphics();
//this.setBackground(Color.BLACK);
//super.paintComponents(g);
backBuffer.setRGB(x, y, Color.BLACK.getRGB());
Graphics bbg = backBuffer.getGraphics();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("map"));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = null;
try {
BufferedImage gray = ImageIO.read(new File("gray.png"));
BufferedImage black = ImageIO.read(new File("black.png"));
while ((line = reader.readLine()) != null) {
for(String s : line.split(""))
{
if (s.contains("*") && xa + 32!= coords.getX() && ya - 32 != coords.getY())
{
bbg.drawImage(gray, xa-32, ya, null);
}
else if (s.contains("#") && xa + 32 != coords.getX() && ya - 32 != coords.getY())
{
bbg.drawImage(black, xa-32, ya, null);
}
if (xa < 320)
{
xa += 32;
}
else
{
ya += 32;
xa = 0;
}
//System.out.println(xa);
//System.out.println(ya);
}
}
} catch (IOException e) {
e.printStackTrace();
}
bbg.setColor(Color.WHITE);
xa = 0;
ya = 0;
System.out.println(coords.getX());
bbg.setColor(Color.WHITE);
bbg.fillRect(coords.getX(),coords.getY(), 32,32);
System.out.println(coords.getY());
//bbg.setColor(Color.BLACK);
//bbg.drawOval(x, y, 20, 20);
g.drawImage(backBuffer, insets.left, insets.top, this);
}
}
Thanks for help.
Check out my code from here, to get a hint as to how to paint stuff in a game loop properly.
Basically what you need to take care of is double buffering to prevent any flickering and also repainting the background so that you don't leave out any trail of rectangles.
You can also check out the Killer Game Programming in Java online book, which can help you learn the game programming concepts and their implementation.
The concept of double buffering is simple. Since painting on the screen takes more time than updating the states of the objects in the gameplay, we use two canvas to prevent any flickering issues which arise when objects are painted directly on the screen.
When the object states are updated in the game loop, it is rendered in a background canvas. The background canvas is then copied to the screen which takes less time compared to painting directly on the screen. And while this copying is happening, the object states are updated again and they are rendered on the background canvas again, which is then copied to the screen. Repeat this over and over, and you get the double buffering.
Basically you keep a buffer of screen which is to be painted and your game renders objects in the buffer which is then copied to the screen.
Here's a code which I think might help you understand the concept:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
public class GamePanel extends JPanel implements Runnable
{
private static final long serialVersionUID = 6892533030374996243L;
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
private Thread animator;
private volatile boolean running = false;
private volatile boolean isGameOver = false;
private volatile boolean isUserPaused = false;
private volatile boolean isWindowPaused = false;
private Graphics dbg;
private Image dbImage = null;
private static final int NO_DELAYS_PER_YIELD = 16;
private static final int MAX_FRAME_SKIPS = 5;
private static final Color backgroundColor = new Color(245, 245, 245);
private static long fps = 30;
private static long period = 1000000L * (long) 1000.0 / fps;
private static volatile boolean isPainted = false;
public GamePanel()
{
setBackground(backgroundColor);
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setFocusable(true);
requestFocus();
readyForPause();
// Add key listeners here...
}
public void addNotify()
{
super.addNotify();
startGame();
}
void startGame()
{
if (animator == null || !running)
{
animator = new Thread(this);
animator.start();
}
}
void stopGame()
{
running = false;
}
private void readyForPause()
{
addKeyListener(new KeyAdapter()
{
public void keyPressed(KeyEvent e)
{
int keyCode = e.getKeyCode();
if ((keyCode == KeyEvent.VK_ESCAPE) || (keyCode == KeyEvent.VK_Q)
|| (keyCode == KeyEvent.VK_END) || (keyCode == KeyEvent.VK_P)
|| ((keyCode == KeyEvent.VK_C) && e.isControlDown()))
{
if (!isUserPaused)
setUserPaused(true);
else
setUserPaused(false);
}
}
});
}
// This is the game loop. You can copy-paste it even in your own code if you want to.
public void run()
{
long beforeTime, afterTime, timeDiff, sleepTime;
long overSleepTime = 0L;
int noDelays = 0;
long excess = 0L;
beforeTime = System.nanoTime();
running = true;
while (running)
{
requestFocus();
gameUpdate();
gameRender();
paintScreen();
afterTime = System.nanoTime();
timeDiff = afterTime - beforeTime;
sleepTime = (period - timeDiff) - overSleepTime;
if (sleepTime > 0)
{
try
{
Thread.sleep(sleepTime / 1000000L);
}
catch (InterruptedException e)
{
}
overSleepTime = (System.nanoTime() - afterTime - sleepTime);
}
else
{
excess -= sleepTime;
overSleepTime = 0L;
if (++noDelays >= NO_DELAYS_PER_YIELD)
{
Thread.yield();
noDelays = 0;
}
}
beforeTime = System.nanoTime();
int skips = 0;
while ((excess > period) && (skips < MAX_FRAME_SKIPS))
{
excess -= period;
gameUpdate();
skips++;
}
isPainted = true;
}
System.exit(0);
}
private void gameUpdate()
{
if (!isUserPaused && !isWindowPaused && !isGameOver)
{
// Update the state of your game objects here...
}
}
private void gameRender()
{
if (dbImage == null)
{
dbImage = createImage(WIDTH, HEIGHT);
if (dbImage == null)
{
System.out.println("Image is null.");
return;
}
else
dbg = dbImage.getGraphics();
}
dbg.setColor(backgroundColor);
dbg.fillRect(0, 0, WIDTH, HEIGHT);
// Render your game objects here....
// like: xyzObject.draw(dbg);
// or dbg.drawOval(...);
if (isGameOver)
gameOverMessage(dbg);
}
private void gameOverMessage(Graphics g)
{
// Paint a game over message here..
}
private void paintScreen()
{
Graphics g;
try
{
g = this.getGraphics();
if ((g != null) && (dbImage != null))
g.drawImage(dbImage, 0, 0, null);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
catch (Exception e)
{
System.out.println("Graphics context error : " + e);
}
}
public void setWindowPaused(boolean isPaused)
{
isWindowPaused = isPaused;
}
public void setUserPaused(boolean isPaused)
{
isUserPaused = isPaused;
}
}
Then you can simply add your game panel to your JFrame like following:
import java.awt.GridBagLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class GameFrame extends JFrame
{
private static final long serialVersionUID = -1624735497099558420L;
private GameFrame gamePanel = new GamePanel();
public GameFrame()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Game");
addWindowListener(new FrameListener());
getContentPane().setLayout(new GridBagLayout());
getContentPane().add(gamePanel);
pack();
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
public class FrameListener extends WindowAdapter
{
public void windowActivated(WindowEvent we)
{
gamePanel.setWindowPaused(false);
}
public void windowDeactivated(WindowEvent we)
{
gamePanel.setWindowPaused(true);
}
public void windowDeiconified(WindowEvent we)
{
gamePanel.setWindowPaused(false);
}
public void windowIconified(WindowEvent we)
{
gamePanel.setWindowPaused(true);
}
public void windowClosing(WindowEvent we)
{
gamePanel.stopGame();
}
}
public static void main(String args[])
{
new GameFrame();
}
}
so i using netbeans, and i'm starting to get into coding games... and i've done this so far with no errors, however when i run it just a grey box with my title "zachs game appears and thats it.... please help if you know the problem 1 -thank you
package swing9;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
public class JavaApplication2 extends JFrame implements Runnable {
int x, y, xDirection, yDirection;
Font font = new Font("Arial", Font.BOLD | Font.ITALIC, 30);
public void run() {
try {
while (true) {
move();
Thread.sleep(5);
}
} catch (Exception e) {
System.out.println("Error");
}
}
public void move() {
x += xDirection;
y += yDirection;
if (x <= 0)
x = 0;
if (x >= 300)
x = 300;
if (y <= 50)
y = 50;
if (y <= 300)
y = 300;
}
public void seyXDir(int xdir) {
xDirection = xdir;
}
public void setYDirection(int ydir) {
yDirection = ydir;
}
public class AL extends KeyAdapter {
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
int setXDirection = -1;
}
if (keyCode == e.VK_RIGHT) {
int setXDirection = +1;
}
if (keyCode == e.VK_UP) {
int setYDirection = -1;
}
if (keyCode == e.VK_DOWN) {
int setYDirection = +1;
}
}
}
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
if (keyCode == e.VK_LEFT) {
int setXDirection = 0;
}
if (keyCode == e.VK_RIGHT) {
int setXDirecetion = 0;
}
if (keyCode == e.VK_UP) {
int setYDirectiom = 0;
}
if (keyCode == e.VK_DOWN) {
int setYDirecction = 0;
}
}
public JavaApplication2() {
addKeyListener((KeyListener) new JavaApplication2.AL());
setTitle("Zachs Game");
setSize(300, 300);
setResizable(false);
setVisible(true);
setBackground(Color.blue);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 150;
y = 150;
}
public void paintComponent(Graphics g) {
g.setColor(Color.red);
g.drawString("Play", 40, 40);
g.setFont(font);
g.setColor(Color.red);
g.fillOval(x, y, 15, 15);
repaint();
}
public static void main(String[] args) {
new JavaApplication2();
// threads
Thread t1 = new Thread();
t1.start();
}
}
JFrame or any of its super classes do not implement the paintComponent method so is never invoked. Check this yourself by adding the #Override annotation.
Move this method to a new class that extends JComponent and invoke super.paintComponent(g) as the first statement.
Don't call repaint from within paintComponent, this create an infinite loop and degrades performance. Swing Timers were designed to interact more easily with swing components. Use these over than raw Threads for periodic updates.
Aside: JFrame is not focusable by default so KeyEvents which require focus will not be triggered without making the window focusable. Use Key Bindings instead.
I have written a small 2d scroller with the assistance of different snippets of code I have found on-line. The original package run as a JFrame application but I am trying to convert it into an applet. When I Run the program in Eclipse I do not receive any debugging errors just a blank applet viewer... I don't think I am missing anything from what I have read from different applet creation sources but maybe it is something very simple.
Frame class
package OurGame;
import java.awt.*;
import javax.swing.*;
public class Frame extends JApplet {
public Frame() {
JPanel frame = new JPanel();
frame.add(new Board());
// frame.setTitle("2D PLATFORMER");
// frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(700,365);
frame.setVisible(true);
//frame.setLocationRelativeTo(null);
//setContentPane(frame);
}
// public static void main(String[] args){
public void init() {
new Frame();
}
}
Ive commented out the containers that were only workable in Jframe.
Dude class
package OurGame;
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Dude {
int x, dx, y,nx,nx2,left, dy;
Image still,jump,reverse;
ImageIcon s = new ImageIcon("redirect.png");
ImageIcon j= new ImageIcon("redirect.png");
ImageIcon l = new ImageIcon("redirect.png");
public Dude() {
x = 75;
left = 150;
nx = 0;
nx2= 685;
y = 172;
still = s.getImage();
}
public void move() {
if (dx != -1){
if (left + dx <= 150)
left+=dx;
else{
x = x + dx;
nx2= nx2+dx;
nx = nx + dx;
}}
else
{
if (left+dx >0)
left = left + dx;
}
}
public int getX() {
return x;
}
public int getnX() {
return nx;
}
public int getnX2() {
return nx2;
}
public int getdx() {
return dx;
}
public Image getImage() {
return still;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
{ dx = -1;
still = l.getImage(); }
if (key == KeyEvent.VK_RIGHT)
{dx = 1;
still = s.getImage();
}
if (key == KeyEvent.VK_UP)
{dy = 1;
still = j.getImage();
} }
public void keyReleased(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT)
dx = 0;
if (key == KeyEvent.VK_RIGHT)
dx = 0;
if (key == KeyEvent.VK_UP)
{dy = 0;
still = s.getImage();}
}
}
Board Class
package OurGame;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Board extends JPanel implements ActionListener, Runnable {
Dude p;
public Image img;
Timer time;
int v = 172;
Thread animator;
boolean a = false;
boolean done2 = false;
public Board() {
p = new Dude();
addKeyListener(new AL());
setFocusable(true);
ImageIcon i = new ImageIcon("redirect.jpg");
img = i.getImage();
time = new Timer(5, this);
time.start();
}
public void actionPerformed(ActionEvent e) {
p.move();
repaint();
}
public void paint(Graphics g) {
if (p.dy == 1 && done2 == false) {
done2 = true;
animator = new Thread(this);
animator.start();
}
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
if ((p.getX() - 590) % 2400 == 0)// p.getX() == 590 || p.getX() == 2990)
p.nx = 0;
if ((p.getX() - 1790) % 2400 == 0)// p.getX() == 1790 || p.getX() == 4190)
p.nx2 = 0;
g2d.drawImage(img, 685 - p.getnX2(), 0, null);
if (p.getX() > 590) {
g2d.drawImage(img, 685 - p.getnX(), 0, null);
}
g2d.drawImage(p.getImage(), p.left, v, null);
if (p.getdx() == -1) {
g2d.drawImage(img, 685 - p.getnX2(), 0, null);
g2d.drawImage(p.getImage(), p.left, v, null);
}
}
private class AL extends KeyAdapter {
public void keyReleased(KeyEvent e) {
p.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
p.keyPressed(e);
}
}
boolean h = false;
boolean done = false;
public void cycle() {
if (h == false)
v--;
if (v == 125)
h = true;
if (h == true && v <= 172) {
v++;
if (v == 172) {
done = true;
}
}
}
public void run() {
long beforeTime, timeDiff, sleep;
beforeTime = System.currentTimeMillis();
while (done == false) {
cycle();
timeDiff = System.currentTimeMillis() - beforeTime;
sleep = 10 - timeDiff;
if (sleep < 0)
sleep = 2;
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
beforeTime = System.currentTimeMillis();
}
done = false;
h = false;
done2 = false;
}
}
I am a little stumbled after doing a fair amount of research. I am thinking Eclipse might not recognise that I have multiple class files but I kind of proved that theory wrong by writing a html page to display my applet that runs fine but is completely empty.
why is the applet viewer even in eclipse blank when running it..
At no point is anything added to the applet container. To add something to the applet would require overriding the applet init() method and calling add(new Board());. (That could also be done in the constructor, but it is more common to build an applet GUI within the init() method.)
Other Notes
paint(Graphics)
Since Board is a Swing class that is not a top-level container, custom painting should be done in the paintComponent(Graphics) method, rather than paint(Graphics).
Nomenclature
JPanel frame = new JPanel();
Wow! Poorly chosen attribute name. What do you call your JFrame instances, panel?
Application resources
ImageIcon s = new ImageIcon("redirect.png");
This will not work for an applet, and would not work for a deployed app. It is necessary to access images by URL. The Applet class has a specific method for loading images.
Remaining lines of constructor
JPanel frame = new JPanel();
frame.add(new Board());
frame.setSize(700,365);
frame.setVisible(true);
The first line of the constructor is not needed, the Board created in the next line can be added directly to the applet. That leaves two more lines not commented out.
frame.setSize(700,365);
The size of an applet should be set by the HTML.
frame.setVisible(true);
Anything added to a component that is visible will itself become visible. As such, this is also redundant.
Swing Timer
Since I pointed out so many faults in the code, just thought I should add that the animation seems to be done correctly - using a Swing Timer. :)