I'm trying to get a simple sprite moving around my screen. I can't get my head around what is wrong with this code as i've followed instructions from a different source code but removed some complexity added from other features in other code.
Right now I'm just trying to get it to move around freely on the screen.
Later I intend for the animation to change while its moving.
Code for both classes is below.
package game;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer:
public class Game extends JPanel implements ActionListener {
int x, y, b_width, b_height;
Player player;
Timer timer;
public Game() {
addKeyListener(new KeyRecorder());
player = new Player();
timer = new Timer(5, this);
timer.start();
}
public void paint(Graphics g){
g.drawImage(player.image, player.getX(), player.getY(), this);
}
#Override
public void actionPerformed(ActionEvent e) {
player.move();
repaint();
}
public class KeyRecorder extends KeyAdapter{
public void keyPressed(KeyEvent e){
player.keyPressed(e);
repaint();
}
public void keyReleased(KeyEvent e){
player.keyReleased(e);
}
}
}
And the sprite:
package game;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class Player {
private String sprite = "sprite.png";
int x, y, dx, dy;
int width, height;
Image image;
public Player() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(sprite));
image = ii.getImage();
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public void move() {
x = x + dx;
y = y + dy;
}
public void keyPressed(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP){
dy -= 3;
}
if(key == KeyEvent.VK_DOWN){
dy += 3;
}
if(key == KeyEvent.VK_LEFT){
dx -= 3;
}
if(key == KeyEvent.VK_RIGHT){
dx += 3;
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if(key == KeyEvent.VK_UP){
dy -= 0;
}
if(key == KeyEvent.VK_DOWN){
dy += 0;
}
if(key == KeyEvent.VK_LEFT){
dx -= 0;
}
if(key == KeyEvent.VK_RIGHT){
dx += 0;
}
}
}
Custom painting is done by overriding the paintComponent() method, not the paint() method.
KeyEvents are only received by comonents with focus. It doesn't look like you panel has focus. In the constructor you need to add:
setFocusable(true);
I don't know a huge amount about swing, but are you calling "repaint()" for every frame you want drawn? For example
thePanel.repaint();
If it flickers, you may also want to set the panel to double buffered
setDoubleBuffered(true);
I hope those helps you anyway. If that doesn't answer your question, perhaps this will http://docs.oracle.com/javase/tutorial/uiswing/painting/ I don't have time to read through it but I did skim it and it looks good.
Related
package testapplication;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
public class TestApplication extends JFrame implements Runnable {
int sizex = 800;
int sizey = 650;
int x, y, xDirection, yDirection;
private Image dbImage;
private Graphics dbg;
Image character;
#Override
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 >= 778)
x = 778;
if(y <= 22)
y = 22;
if(y >= 628)
y = 628;
}
public void setXDirection(int xdir){
xDirection = xdir;
}
public void setYDirection(int ydir){
yDirection = ydir;
}
Font font = new Font("Arial", Font.BOLD, 30);
public class AL extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
//Key press inputs "WASD"
if(keyCode == KeyEvent.VK_W) {
setYDirection(-1);
}
if(keyCode == KeyEvent.VK_A) {
setXDirection(-1);
}
if(keyCode == KeyEvent.VK_S) {
setYDirection(+1);
}
if(keyCode == KeyEvent.VK_D) {
setXDirection(+1);
}
//end Key press inputs "WASD"
}
#Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
//Key release inputs "WASD"
if(keyCode == KeyEvent.VK_W) {
setYDirection(0);
}
if(keyCode == KeyEvent.VK_A) {
setXDirection(0);
}
if(keyCode == KeyEvent.VK_S) {
setYDirection(0);
}
if(keyCode == KeyEvent.VK_D) {
setXDirection(0);
}
//end Key release inputs "WASD"
}
}
public TestApplication() {
//Load images
ImageIcon i = new ImageIcon("C:/Users/Min/Documents/NetBeansProjects/TestApplication/src/testapplication/Untitled-1.png") {};
character = i.getImage();
//Game properties
addKeyListener(new AL());
setTitle("TestApplication");
setSize(sizex, sizey);
setResizable(false);
setVisible(true);
setBackground(Color.LIGHT_GRAY);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
x = 30;
y = 628;
}
#Override
public void paint(Graphics g) {
dbImage = createImage(getWidth(), getHeight());
dbg = dbImage.getGraphics();
paintComponent(dbg);
g.drawImage(dbImage, 0, 0, this);
}
public void paintComponent(Graphics g) {
g.setFont(font);
g.setColor(Color.RED);
g.drawString("Welcome to TESTTEST", 300,125);
g.setColor(Color.RED);
g.drawImage(character, x, y, this);
repaint();
}
public static void main(String[] args) {
TestApplication ta = new TestApplication();
//Threads
Thread t1 = new Thread();
t1.start();
}
}
In my Java code, there is supposed to be an image that moves using the WASD keys. The image shows, yet it will not move. What's wrong?
This is a simple Java code that is supposed to make an image roam around the window with WASD keys. I am not sure what I did wrong in the code, I've double checked and everything looked fine...
First of all, if you need to change the image location while the user presses one of the wsda keys then you need to add 1 and -1 to the current value of x and y ( image location). You just set 1 and -1 which will move the image just one pixel even if, for example, you press the d button multiple times over and over.
You need to change method setXDirection to this (I have added a plus before the equal sign to add xDir value to whatever xDirection is.)
public void setXDirection(int xDir)
{
xDirection += xDir
}
Make the same correction with yDirection (yDirection += yDir)
Second, you don't call your paint method. You have to call it each time your user presses a key (one of wasd ofcourse), so do it at the final line of your keyReleased method.
I hope these two correct your code but I think you need to recheck the code again with much care.
Good luck,
Iman
You forgot to add the Runnable instance to the Thread constructor.
Your main method should be:
public static void main(String[] args) {
TestApplication ta = new TestApplication();
//Threads
Thread t1 = new Thread(ta);
t1.start();
}
So I have this little project where I make the mario jump. But I can't figure out how to repaint it. If I do it in the Main class after a click, then the whole jumping will be very jerky.
I tried to do it at the end of my jump function but that did not work too.
Here is my code:
Main:
package klassid;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;
public class Main extends JComponent implements KeyListener, ActionListener{
static Hero hero;
Timer t = new Timer(500,this);
public static void main(String[] args) {
JFrame aken = new JFrame("Simple jumping simulator");
aken.setSize(600, 600);
aken.getContentPane().setBackground(new Color(255,255,255));
aken.getContentPane().add(new Main());
aken.setVisible(true);
aken.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
hero.the_jump();
}
public Main(){
addKeyListener(this);
setFocusable(true);
t.start();
hero = new Hero(0, 320);
}
public void paintComponent(Graphics g){
hero.render(g, this);
g.setColor(Color.GREEN);
g.fillRect(0, 550, 600, 2);
}
#Override
public void keyPressed(KeyEvent e) {
hero.move(e.getKeyCode());
}
public void keyReleased(KeyEvent e) {
hero.move2(e.getKeyCode());
}
public void keyTyped(KeyEvent e) {}
public void actionPerformed(ActionEvent e) {}
}
And my Hero class:
package klassid;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.Graphics;
public class Hero {
static Main main;
int y;
Image pilt = Toolkit.getDefaultToolkit().getImage("../mario.png");
private double height = 0, speed = 4;
public static final double gravity = 9.81;
private double x = 25;
private boolean left = false, right = false, up = false;
public Hero(int x, int y){
this.x = x;
this.y = y;
}
public void render(Graphics g, Main pohiKlass){
g.drawImage(pilt, (int) (x), (int) (500-(height*100)), 50, 50, pohiKlass);
}
public void the_jump() {
long previous = 0, start = 0;
while(true){
start= System.nanoTime();
if(previous != 0 && up){
double delta = start - previous;
height += (delta/1000000000) * speed;
speed -= (delta/1000000000) * gravity;
}
if(left)
x -= 3;
if(right)
x += 3;
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
if(height < 0){
height = 0;
speed = 4;
up = false;
}
previous = start;
repaint();
}
}
public void move(int i){
if(i == 38)
up=true;
if(i == 37)
left=true;
if(i == 39)
right=true;
}
public void move2(int i){
if(i == 37)
left=false;
if(i == 39)
right=false;
}
}
I also tried to access the paintComponent in the_jump function but it did not work as I have no idea what kind of a parameter it expects.
How is this mess solvable?
The first line in your paintComponent method should be:
super.paintComponent(g);
JComponent will do a lot of things for you, but you need to explicitly call the super class method to do so. Take a look at the Oracle Documentation here.
You could call repaint() in your actionPerformed method, if you decrease the timer value to something very low. This will give you "continuous" repainting (as many times a second as you can reasonably perform).
I'm trying to create the beginning of a simple game. The first thing I am trying to do is import a graphic into my code and move it across the screen. I was able to draw a ball on the screen and move it around but when I import a graphic from a file I am unable to move it around. What am I missing or doing wrong?
import javax.swing.*;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Game extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
double x = 0, y = 0, velX = 0, velY = 0;
private ImageIcon image;
public Game(){
setBackground(Color.WHITE);
t.start();
addKeyListener(this);
this.setFocusable(true);
setFocusTraversalKeysEnabled(false);
image = new ImageIcon ("ship.gif");
}
public void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon i = new ImageIcon("C:\\Users\\Bryan\\Pictures\\ship.gif");
i.paintIcon(this, g, 0, 0);
}
public void actionPerformed(ActionEvent e){
repaint();
x += velX;
y += velY;
if(x<0){
velX = 0;
x = 0;
}
if(x>750){
velX = 0;
x = 750;
}
if(y<0);{
velY = 0;
y = 0;
}
if(y>550){
velY = 0;
y = 550;
}
}
public void up(){
velY = -1.5;
velX = 0;
}
public void down(){
velY = 1.5;
velX = 0;
}
public void left(){
velX = -1.5;
velY = 0;
}
public void right(){
velX = 1.5;
velY = 0;
}
public void keyPressed(KeyEvent e){
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP){
up();
}
if (code == KeyEvent.VK_DOWN){
down();
}
if (code == KeyEvent.VK_LEFT){
left();
}
if (code == KeyEvent.VK_RIGHT){
right();
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e){
// velX = 0;
// velY = 0;
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP){
velY = 0;
}
if (code == KeyEvent.VK_DOWN){
velY = 0;
}
if (code == KeyEvent.VK_LEFT){
velX = 0;
}
if (code == KeyEvent.VK_RIGHT){
velX = 0;
}
}
}
My driver is in another class as follows:
import java.awt.Color;
import javax.swing.JFrame;
public class GameDriver {
public static void main(String[] args) {
JFrame f = new JFrame();
Game g = new Game();
f.add(g);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(800,600);
}
}
Two big problems here:
public void paintComponent(Graphics g){
super.paintComponent(g);
ImageIcon i = new ImageIcon("C:\\Users\\Bryan\\Pictures\\ship.gif");
i.paintIcon(this, g, 0, 0);
}
You're reading from a file from within paintComponent(...). Never do this as this will slow your drawing unnecessarily. Read the image once, perhaps in a constructor, and then use the stored image variable in drawing. The paintComponent method should be for painting only, and it should be lean, mean and fast.
You're drawing at 0, 0 always. If you want to move something, draw at a variable position, and then change the values held by the variable and repaint.
Also: You should use Key Bindings to accept key strokes in a Swing application as this will help solve focus issues.
For example, please have a look at my code in this answer.
first sorry for my bad English
Hello everyone I'm developing a 2d game using java and when a want to animate a sequence of images only the last image is loaded & i don't know why my code seems Logic
So that when I press "Q" button there most be an animation there.
code:
Dude Class
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Dude {
int x, dx, y, dy;
Image still;
Image walking;
Image effet;
ImageIcon i = new ImageIcon("C:/1.gif");
ImageIcon run=new ImageIcon("C:/NeroRun.gif");
ImageIcon down=new ImageIcon("C:/nero_down.gif");
Image[]attack=new Image[15];
ImageIcon saut_effet=new ImageIcon("C:/saut_effet.gif");
ImageIcon saut=new ImageIcon("C:/saut.gif");
ImageIcon effect=new ImageIcon("C:/saut_effet.gif");
//ImageIcon attack;
public Dude() throws {
still = i.getImage();
x = 10;
y = 260;
for(int j=0;j<15;j++){
ImageIcon ii=new ImageIcon("C:/Games/frame-"+(j+1)+".gif");
attack[j] = ii.getImage();
System.out.println("Nice");
}
}
public void move(){
x = x + dx;
y = y + dy;
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public Image getImage(){
return still;
}
public Image getEffet(){
return effet;
}
public void keyPressed(KeyEvent e) throws InterruptedException{
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -3;
still=run.getImage();
System.out.println("Left");
if(y==260){y+=55;}
}
if (key == KeyEvent.VK_RIGHT) {
dx = 3;
still=run.getImage();
System.out.println("Right");
if(y==260){y+=55;}
effet=null;
}
if (key == KeyEvent.VK_DOWN) {
still=down.getImage();
System.out.println("Down");
if(y==260){y+=90;}
effet=null;
}
if (key == KeyEvent.VK_UP){
if(y==260){y-=130;}
effet=effect.getImage();
still=saut.getImage();
}
if(key == KeyEvent.VK_Q){
if(y==260){y-=135;
for(int j=0;j<15;j++){
still=attack[j];
}
//attack=new ImageIcon("C:/first_attack.gif");
//still=attack.getImage();}
effet=null;
}
}
}
public void keyReleased(KeyEvent e){
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT){
dx = 0;
still=i.getImage();
y=260;
effet=null;
}
if (key == KeyEvent.VK_RIGHT){
dx = 0;
still=i.getImage();
y=260;
effet=null;
}
if (key == KeyEvent.VK_DOWN){
dx = 0;
still=i.getImage();
y=260;
effet=null;
}
if (key == KeyEvent.VK_UP){
still=i.getImage();
y=260;
effet=null;
}
if (key == KeyEvent.VK_Q){
still=i.getImage();
y=260;
effet=null;
}
}
}
Borad1 Class:
package FirstTest;
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 java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import javax.swing.Timer;
import org.newdawn.slick.SlickException;
/**
*
* #author SiLeNT J0cK3R
*/
class Board1 extends JPanel implements ActionListener{
Dude p;
Image img;
Timer time;
public Board1() throws SlickException{
p = new Dude();
addKeyListener(new AL());
setFocusable(true);
ImageIcon i = new ImageIcon("C:/Background.png");
img = i.getImage();
time = new Timer(5, this);
//Music.music();
time.start();
}
#Override
public void actionPerformed(ActionEvent e){
p.move();
repaint();
//System.out.println("Repaint");
}
#Override
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(img, 0, 0, null);
g2d.drawImage(p.getImage(), p.getX(), p.getY(),null);
//Pour animer les effets loresequ'on effectue un saut
g2d.drawImage(p.getEffet(),p.getX(),300,null);
//Pour animer les ennemies
}
private class AL extends KeyAdapter{
#Override
public void keyReleased(KeyEvent e){
p.keyReleased(e);
}
#Override
public void keyPressed (KeyEvent e){
try {
p.keyPressed(e);
} catch (InterruptedException ex) {
Logger.getLogger(Board1.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
for(int j=0;j<15;j++){
still=attack[j];
}
When identifying the Q key, you seem to just walk through the animation frames (images).For an animation to be visible, some time would have to pass between each change of an animation frame.
I would suggest you take a look at some examples and tutorials. Like the Space Invaders clone found here: www.cokeandcode.com
I'm kind of a beginner when it comes to java programming, and I have a project in school where I'm going to create a game much like Icy Tower. And my question is, how am I going to write to make the character stand on the ground and be able to jump up on objects?
Here's my code so far:
Part one
package Sprites;
import java.awt.Image;
import java.awt.event.KeyEvent;
import javax.swing.ImageIcon;
public class jumper {
private String jump = "oka.png";
private int dx;
private int dy;
private int x;
private int y;
private Image image;
public jumper() {
ImageIcon ii = new ImageIcon(this.getClass().getResource(jump));
image = ii.getImage();
x = 50;
y = 100;
}
public void move() {
x += dx;
y += dy;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public Image getImage() {
return image;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = -5;
ImageIcon ii = new ImageIcon(this.getClass().getResource("oki.png"));
image = ii.getImage();
}
if (key == KeyEvent.VK_RIGHT){
dx = 5;
ImageIcon ii = new ImageIcon(this.getClass().getResource("oka.png"));
image = ii.getImage();
}
if (key == KeyEvent.VK_SPACE) {
dy = -5;
}
if (key == KeyEvent.VK_DOWN) {
dy = 5;
}
}
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_SPACE) {
dy = 0;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
}
Part two
package Sprites;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JPanel;
import javax.swing.Timer;
public class board extends JPanel implements ActionListener {
private Timer klocka;
private jumper jumper;
public board() {
addKeyListener(new TAdapter());
setFocusable(true);
setBackground(Color.WHITE);
setDoubleBuffered(true);
jumper = new jumper();
klocka = new Timer(5, this);
klocka.start();
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D)g;
g2d.drawImage(jumper.getImage(), jumper.getX(), jumper.getY(), this);
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
public void actionPerformed(ActionEvent e) {
jumper.move();
repaint();
}
private class TAdapter extends KeyAdapter {
public void keyReleased(KeyEvent e) {
jumper.keyReleased(e);
}
public void keyPressed(KeyEvent e) {
jumper.keyPressed(e);
}
}
}
Part three
package Sprites;
import javax.swing.JFrame;
public class RType extends JFrame {
public RType() {
add(new board());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLocationRelativeTo(null);
setTitle("R - type");
setResizable(false);
setVisible(true);
}
public static void main(String[] args) {
new RType();
}
}
I really appreciate all the help I can get!
This might help. It's a set of tutorials aimed at helping people make tile-based games. Including side-on platform games. See http://www.tonypa.pri.ee/tbw/tut07.html. By the way, you're doing quite intensive image-loading stuff in the character movement methods. Don't do that. Cache the images first. Also, you can double-buffer your Canvas to make it smooth. See the code here for details.