This question already has answers here:
How to use Key Bindings instead of Key Listeners
(4 answers)
Closed 5 years ago.
When VK_UP or VK_DOWN is pressed the Graphic g I created is not changing its position whatsoever. If someone could look and see if there is something wrong with my move method etc. Would really appreciate it.
Here is all my code so far:
package ping2;
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Ping2 extends Applet implements Runnable, KeyListener{
final int WIDTH = 700, HEIGHT = 500;
Thread thread;
UserPaddle user1;
public void init() {
this.resize(WIDTH, HEIGHT);
this.addKeyListener(this);
user1 = new UserPaddle(1);
thread = new Thread(this);
thread.start();
}
public void paint(Graphics g) {
g.setColor(Color.black);
g.fillRect(0, 0, WIDTH, HEIGHT);
user1.draw(g);
}
public void update(Graphics g) {
paint(g);
}
public void run() {
for(;;) {
user1.move();
repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
user1.setUpAccel(true);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
user1.setDownAccel(true);
}
}
public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP) {
user1.setUpAccel(false);
}
else if(e.getKeyCode() == KeyEvent.VK_DOWN) {
user1.setDownAccel(false);
}
}
public void keyTyped(KeyEvent arg0) {
}
}
package ping2;
import java.awt.*;
public class UserPaddle implements InterfaceBar{
double y, yVelocity;
boolean upAccel, downAccel;
int player1, x;
final double FRICTION = 0.90;
public UserPaddle(int player1) {
upAccel = false;
downAccel = false;
y = 210;
yVelocity = 0;
if(player1 == 1)
x = 20;
else
x = 660;
}
public void draw(Graphics g) {
g.setColor(Color.white);
g.fillRect(x, (int)y, 20, 80);
}
public void move() {
if(upAccel) {
yVelocity -= 2;
}else if(downAccel) {
yVelocity += 2;
}
//Automatically slows bar down if key not being pressed.
else if(!upAccel && !downAccel) {
yVelocity *= FRICTION;
}
}
public void setUpAccel(boolean input) {
upAccel = input;
}
public void setDownAccel(boolean input) {
downAccel = input;
}
public int getY() {
return (int)y;
}
}
package ping2;
import java.awt.Graphics;
public interface InterfaceBar {
public void draw(Graphics g);
public void move();
public int getY();
}
I have modified your move() a bit give it a try
move()
public void move() {
if(upAccel) {
yVelocity -= 2;
y = yVelocity;
}else if(downAccel) {
yVelocity += 2;
y = yVelocity;
}
}
Related
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class snakeGame extends Applet implements Runnable, KeyListener{
private snake snk = new snake();
private Thread thread;
private Graphics gfx;
private Image img;
private boolean game = true;
public void init(){
setBackground(Color.black);
this.setSize(new Dimension(800,800));
this.addKeyListener(this);
img = createImage(800, 800);
gfx = img.getGraphics();
thread = new Thread();
thread.start();
}
public void paint(Graphics g){
//g.setColor(Color.white);
//g.fillRect(snk.getX(), snk.getY(), 10, 10);
snk.draw(g);
}
public void update(Graphics g){
paint(g);
}
public void repaint(Graphics g){
paint(g);
}
public void run(){
while(game){
//snk.move();
if(snk.getDiry() == -1){
snk.y -= 10;
}
if(snk.getDiry() == 1){
snk.y += 10;
}
if(snk.getDirx() == -1){
snk.x -= 10;
}
if(snk.getDirx() == 1){
snk.x += 10;
}
repaint();
try{
Thread.sleep(200);
}
catch(InterruptedException e){
e.printStackTrace();
}
}
}
public void keyPressed(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_UP){
snk.setDirx(0);
snk.setDiry(-1);
System.out.println("UP");
}
else if (e.getKeyCode() == KeyEvent.VK_DOWN){
snk.setDirx(0);
snk.setDiry(1);
System.out.println("DOWN");
}
else if (e.getKeyCode() == KeyEvent.VK_LEFT){
snk.setDirx(-1);
snk.setDiry(0);
System.out.println("LEFT");
}
else if (e.getKeyCode() == KeyEvent.VK_RIGHT){
snk.setDirx(1);
snk.setDiry(0);
System.out.println("RIGHT");
}
else{
System.out.println("Wrong key pressed");
}
}
public void keyReleased(KeyEvent e){
}
public void keyTyped(KeyEvent e){
}
}
This is the code for the snakeGame class. There is one other file named "snake.java" which contains accessors and mutators for the variables and defination of draw function. This is the snake.java
import java.awt.*;
public class snake {
public int x, y;
private int dirx, diry;
public snake(){
this.x = 400;
this.y = 400;
this.dirx = 0;
this.diry = 1;
}
public void draw(Graphics g){
g.setColor(Color.white);
g.fillRect(getX(), getY(), 20, 20);
}
public int getX(){
return x;
}
public int getY(){
return y;
}
public int getDirx(){
return dirx;
}
public int getDiry(){
return diry;
}
public void setDirx(int dirx){
this.dirx = dirx;
}
public void setDiry(int diry){
this.diry = diry;
}
}
The snake won't show up in the applet window. Please help me see what is wrong in the code and how it can be made better. I am new with coding and StackOverflow so please forgive me if I have made some stupid mistake.
Thanks in advance
PEACE
A friend and I are starting to make a simple Java game and my job was to make a JFrame that has a player block that can jump on a platform. I am able to make the player class by making it extend Block.
I have reached a point where I can draw the player, but it only moves up and won't come back down, and the block thats supposed to be the floor wont show up. Here is my Main method, Block and Player classes, respectively.
package michael.s.game;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class MichaelSGame {
/**
* #param args the command line arguments
*/
static JFrame frame = new JFrame("Lab 54");
static JPanel panel;
static int height = (int)Toolkit.getDefaultToolkit().getScreenSize().getHeight();
static int width = (int)Toolkit.getDefaultToolkit().getScreenSize().getWidth();
static Player player = new Player(5,5,height - 20,width/2,0,0,Color.BLUE);
static Block floor = new Block(10,width,width,height - 20,Color.GREEN){
#Override
public void update() {
if(isTouching(player))
player.vy=0;
}
};
public static void main(String[] args) {
panel = new JPanel(){
//#Override
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.GREEN);
floor.paint(g);
player.paint(g);
}
};
panel.setBackground(Color.white);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setBounds(0,0,width,height);
frame.setUndecorated(true);
KeyListener controls = new KeyListener(){
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE)
{
player.jump();
}
if(e.getKeyCode() == KeyEvent.VK_LEFT){
player.left();
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
{
player.right();
}
}
#Override
public void keyReleased(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
player.stop();
}
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
{
player.stop();
}
if(e.getKeyCode() == KeyEvent.VK_SPACE)
{
player.stop();
}
}
};
frame.add(panel);
panel.setFocusable(true);
panel.addKeyListener(controls);
panel.addKeyListener(new KeyAdapter(){
#Override
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
System.exit(0);
}
});
frame.setVisible(true);
new Thread(new Runnable(){
#Override
public void run() {
try{
while(true){
floor.update();
player.update();
panel.repaint();
Thread.currentThread().sleep(10);
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}).start();
}
}
///////////////////////////////
package michael.s.game;
import java.awt.Color;
import java.awt.Graphics;
/**
*
* #author David
*/
public abstract class Block {
protected int ht;
protected int wt;
protected double x;
protected double y;
protected Color color;
public Block(int ht, int wt, double x, double y, Color color)
{
this.ht = ht;
this.wt = wt;
this.x = x;
this.y = y;
this.color = color;
}
public boolean isTouching(Block other)
{
return x+wt >= other.getX() && other.getX() + other.getWt() >= x && y+ht >= other.getY() && other.getY() + other.getHt() >= y;
}
public int getX()
{
return (int) x;
}
public int getY()
{
return (int) y;
}
public int getHt()
{
return this.ht;
}
public int getWt()
{
return this.wt;
}
public void paint(Graphics g)
{
g.setColor(color);
g.fillRect(getX(), getY(), wt, ht);
}
public abstract void update();
}
/////////////////
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package michael.s.game;
import java.awt.Color;
/**
*
* #author David
*/
public class Player extends Block
{
public double vx;
public double vy;
public double GRAVITY;
public Player(int ht, int wt, double x, double y, double vx, double vy, Color color)
{
super(ht,wt,x,y, color);
}
#Override
public void update()
{
vy+= GRAVITY;
x+=vx;
y+=vy;
}
public void left()
{
vx = -5;
}
public void right()
{
vx = 5;
}
public void jump()
{
vy = -10;
}
public void stop()
{
vy = 0;
}
}
How can I get gravity to work in this, and have the floor actually show up?
I need help on adding a gravity function, having the floor show itself, and having the player stop when the player hits the floor.
I've switched from KeyListeners to KeyBindings as instructed, however they still seem to do nothing. My keybinds are set up as to allow the left and right arrow keys to call a setDx() method in paddle.java which instructs the move() method to move the paddle.
gamePanel.java:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class gamePanel extends JPanel implements ActionListener {
paddle Paddle;
boolean ingame = true;
int delay = 1000;
Timer timer;
JLabel text = new JLabel("stuff here");
InputMap im = this.getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
ActionMap am = this.getActionMap();
public gamePanel() {
setBackground(Color.WHITE);
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "RightArrow");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "LeftArrow");
add(text);
text.setBounds(100, 100, 200, 300);
timer = new Timer(delay, this);
Paddle = new paddle();
timer.start();
}
#Override
public void paint(Graphics g) {
super.paint(g);
if (ingame) {
g.drawImage(Paddle.getImage(), Paddle.getX(), Paddle.getY(),
Paddle.getWidth(), Paddle.getHeight(), this);
}
}
#Override
public void actionPerformed(ActionEvent ae) {
Object obj = ae.getSource();
if (obj == timer) {
Paddle.move();
validate();
repaint();
}
}
public class ArrowAction extends AbstractAction {
private String cmd;
public ArrowAction(String cmd) {
this.cmd = cmd;
}
#Override
public void actionPerformed(ActionEvent e) {
if (cmd.equalsIgnoreCase("LeftArrow")) {
Paddle.setDx(-20);
} else if (cmd.equalsIgnoreCase("RightArrow")) {
Paddle.setDx(20);
}
}
}
/*
#Override
public void keyPressed(KeyEvent ke) {
int KeyCode = ke.getKeyCode();
if (KeyCode == KeyEvent.VK_LEFT) {
text.setText("key pressed");
Paddle.setDx(-20);
}
if (KeyCode == KeyEvent.VK_RIGHT) {
Paddle.setDx(20);
}
}
#Override
public void keyReleased(KeyEvent ke) {
int KeyCode = ke.getKeyCode();
if (KeyCode == KeyEvent.VK_LEFT) {
Paddle.setDx(0);
}
if (KeyCode == KeyEvent.VK_RIGHT) {
Paddle.setDx(0);
}
}
#Override
public void keyTyped(KeyEvent ke) {
}
*/
}
Paddle.java:
import java.awt.Image;
import java.awt.Rectangle;
import javax.swing.ImageIcon;
public class paddle {
int dx = 0;
int x, y;
int height, width;
Image image;
public paddle() {
ImageIcon ii = new ImageIcon("src/Paddle.png");
image = ii.getImage();
width = image.getWidth(null);
height = image.getHeight(null);
//dx = 20;
resetState();
}
public void setDx(int z) {
dx = z;
}
public void move() {
x += dx;
if (x <= 2) {
x = 2;
}
if (x >= (640 - getWidth())) {
x = (640 - getWidth());
}
}
public void resetState() {
x = 250;
y = 375;
}
public void setX(int x) {
this.x = x;
}
public int getX() {
return x;
}
public void setY(int y) {
this.y = y;
}
public int getY() {
return y;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
Image getImage() {
return image;
}
Rectangle getRect() {
return new Rectangle(x, y, image.getWidth(null), image.getHeight(null));
}
}
If your KeyListener methods are not being called I suspect it's because the correct component does not have focus. It's difficult sometimes to manage what component has focus especially in a game, so I would suggest switching over to using key bindings which doesn't require components to have focus.
You never add the corresponding actions you the ActionMap
am.put("LeftArrow", new ArrowAction("LeftArrow"));
am.put("RightArrow", new ArrowAction("RightArrow"));
Also, if you don't repaint() in the actioPerformed of the ArrowAction, you won't see it update immediately, until repaint() is called by the Timer, which isn't very long, but still a miniscule delay.
I have some code that makes 273 black squires on the screen but yet they only show up for a second. I know its something wrong with the repaint but i can't find it.
import java.applet.*;
import java.util.*;
import java.awt.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.*;
public class Start extends Applet implements Runnable, KeyListener
{
public boolean running = true;
int fall = 60;
int count = 0;
Thread thread;
private Image i;
private Graphics doubleG;
Brick b[] = new Brick[273];//abtsert class
public int[] x = {270,300,330,360,390,420,450,480,510,540,570,600,630};
public int[] y = {-10,20,50,80,110,140,170,200,230,260,290,320,350,380,410,440,470,500,530,560,590,620,650};
public boolean[] bl = {false,true};
public int[] color = {0,1,2,3,4};
public int xc = 0;//indx of x
public int yc = 0;//indx of y
public int indx = 0;//indx of b
public int start = 0;
public void init()
{
Arrays.fill(b,new Background());
addKeyListener(this);
setFocusable(true);
thread = new Thread(this);
thread.start();
}
public void run()
{
while(running)
{
try
{
thread.sleep(17);
}
catch(InterruptedException e)
{
}
repaint();
}
}
public void paint(Graphics g)
{
resize(700,700);
if(start == 0)
{
set(g);//sets fills b with objects
start = 1;
}
else//prints out the abjects stored in b[]
{
while(indx != 273)
{
b[indx].paint(g);
indx++;
}
indx=0;
}
g.drawRect(300,50,300,600);
}
public void update(Graphics g)
{
if(i == null)
{
i = createImage(this.getSize().width, this.getSize().height);
doubleG = i.getGraphics();
}
doubleG.setColor(getBackground());
doubleG.fillRect(0,0,700,700);
doubleG.setColor(getForeground());
paint(doubleG);
g.drawImage(i,0,0,this);
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == e.VK_LEFT)
{
}
if(e.getKeyCode() == e.VK_RIGHT)
{
}
repaint();
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void set(Graphics g)
{
while(yc <= 22)
{
b[indx].start(g,x[xc],y[yc]);
if(xc <= 12)
{
xc++;
}
if(xc == 12)
{
yc++;
xc=0;
}
indx++;
}
yc=0;
indx=0;
}
}
this is the abstract class
import java.applet.*;
import java.util.*;
import java.awt.*;
public abstract class Brick
{
public int px;
public int py;
public abstract void paint(Graphics g);
public abstract void start(Graphics g ,int x ,int y);
}
this is the class that uses the abstract class
import java.applet.*;
import java.util.*;
import java.awt.*;
public class Background extends Brick//thing thats being painted
{
public int px;//where the x,y are stored
public int py;
public void paint(Graphics g)//used to repaint it
{
g.setColor(Color.BLACK);
g.fillRect(px,py,29,29);
}
public void start(Graphics g,int x, int y)//used to set the object
{
g.setColor(Color.BLACK);
g.fillRect(x,y,29,29);
px = x;
py = y;
}
}
can you see the problem. the thread runs fine but the brick does not want to respond to the key listener. I try to test if the keylistener was at last getting an event but it does not even do the system.out.println
import java.awt.*;//imports
import java.util.*;
import java.applet.*;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class Start extends Applet implements Runnable, KeyListener// where i put the keylistener in
{
DrawBackground dbg = new DrawBackground();
Brick brick = new Brick();
Thread gameLoop;
public void init() {
addKeyListener(this);// i add the key listener
}
public void start() {
Thread gameLoop = new Thread(this);
gameLoop.start();
}
public void run() {
while (true) {
brick.update(1);
repaint();
try {
Thread.sleep(17);
}
catch (InterruptedException e) {
}
}
}
public void stop() {
}
public void paint(Graphics g)// with out any paint it works if im changing
// somthing like a lable
{
dbg.paint(g, this);
brick.paint(g, this);
}
public void keyPressed(KeyEvent e)// test to see if it works
{
System.out.println("why");
if (e.getKeyCode() == 37) {
brick.left();
}
}
public void keyTyped(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
}
}
this is the Brick class the thing i'm trying to move
import java.awt.*;
import java.util.*;
import java.applet.*;
public class Brick {
public int dy = 40;
public int yStart = -20;
public int time = 0;
public int dx = 0;
public int xStart = 0;
public int start = 1;
public void paint(Graphics g, Start sp) {
Dimension screenSize = sp.getSize();
int sheight = screenSize.height;
int swidth = screenSize.width;
if (start == 1) {
xStart = swidth - (int) (swidth / 2.5);
start = 0;
}
int bWidth = swidth / 15;
int bHeight = swidth / 15;
int time = 0;
g.setColor(Color.red);
g.fillRect(xStart, yStart, bWidth, bHeight);
}
public void update(int x) {
if (time == 60) {
time = 0;
yStart += dy;
}
else {
time += x;
}
}
public void left() {
xStart -= dx;
}
}
It doesn't look like you have set the keyboard focus. See this question.
I've always used setFocusable(true) after adding the keyListener and its worked for me, but the answer to that question has a better solution.