Having Trouble Moving Object in Java [duplicate] - java

This question already has an answer here:
Move a BALL on Jpanel with keyboard down key
(1 answer)
Closed 6 years ago.
I tried to create a ball that moves when I click the arrow buttons. When I click the arrow buttons, though, the ball does not respond. I tried to create a ball that moves when I click the arrow buttons. When I click the arrow buttons, though, the ball does not respond. Here's my code:
package ball.main;
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.JPanel;
import javax.swing.Timer;
public class Ball extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(5, this);
int x = 0;
int y = 0;
int velX;
int velY;
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.GREEN);
g.fillOval(x, y, 20, 20);
t.start();
}
#Override
public void actionPerformed(ActionEvent e) {
if (x < 0) {
x = 0;
}
if (x > 580) {
x = 580;
}
if (y < 0) {
y = 0;
}
if (y > 580) {
y = 580;
}
x += velX;
x += velY;
repaint();
}
#Override
public void keyPressed(KeyEvent e) {
int code = e.getKeyCode();
if (code == KeyEvent.VK_UP) {
velY = -1;
}
if (code == KeyEvent.VK_DOWN) {
velY = 1;
}
if (code == KeyEvent.VK_RIGHT) {
velX = 1;
}
if (code == KeyEvent.VK_LEFT) {
velX = -1;
}
}
#Override
public void keyReleased(KeyEvent e) {
velX = 0;
velY = 0;
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}
What is wrong with my code?

The answer is to use Key Bindings instead of KeyListener

Related

How to use KeyListener for moving Rectangles

I am trying to move a rectangle while the key is pressed and to stop it on release like the game "Snake". As reference I followed this tutorial.
I tried to adjust a few things in my code:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.Graphics;
import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
public class f3 extends JPanel implements ActionListener, KeyListener {
static JFrame frame;
static Timer t;
static int x, y, velx, vely, c;
f3(){
t = new Timer(5, this);
x = 0;
y = 0;
velx = 0;
vely = 0;
frame = new JFrame();
frame.addKeyListener(this);
frame.setFocusable(true);
frame.setFocusTraversalKeysEnabled(false);
frame.setSize(500,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this);
frame.setVisible(true);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.BLUE);
g.fillRect(x, y, 50, 30);
t.start();
}
public void actionPerformed(ActionEvent e) {
x = x + velx;
y = y + vely;
repaint();
}
public void keyPressed(KeyEvent e) {
c = e.getKeyCode();
if(c == KeyEvent.VK_RIGHT) {
velx = 1;
vely = 0;
}
if(c == KeyEvent.VK_LEFT) {
velx = -1;
vely = 0;
}
if(c == KeyEvent.VK_UP) {
velx = 0;
vely = -1;
}
if(c == KeyEvent.VK_DOWN) {
velx = 0;
vely = 1;
}
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
public static void main(String args[]) {
new f3();
}
}
The value of velx and vely are set after a key event is triggered. Since you are using a Timer here, the GUI will continuously update because actionPerformed is repeatedly triggered.
Remove the Timer, then put the change section of keyPressed to this form and you will get a desired result.
public void keyPressed(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_RIGHT){
velx = 1;
vely = 0;
x = x + velx;
y = y + vely;
repaint();
}
}
Since velx and vely indicate the velocity of the movement (as opposed to moving the player one space at a time, for instance), you will want to also ensure keyReleased returns the appropriate velocity to 0 when the specific key associated with that axis is released.
You do not have a handler for keyReleased method, where you should set velocities to zero as such:
public void keyReleased(KeyEvent e) {
velx = 0;
vely = 0;
}

Moving graphics with arrow keys with java

I am trying to make a rectangle move with arrow keys (for a game) but I am getting an error message. It says this, but it still doesnt work when I change it. I have tried multiple times but still receive the same error. Does anyone know why this error is appearing?
this is the error:
java.lang.Error: Do not use javax.swing.JFrame.add() use javax.swing.JFrame.getContentPane().add() instead
at javax.swing.JFrame.createRootPaneException(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at Tutorial.main(Tutorial.java:109)
Here is my code:
// The "Test" class.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Tutorial extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer (5,this);
int x = 0, y = 0, velX = 0, velY = 0;
public Tutorial ()
{
tm.start();
addKeyListener(this);
setFocusable (true);
setFocusTraversalKeysEnabled(false);
}
public void paintComponent (Graphics g)
{
super.paintComponent (g);
g.setColor (Color.RED);
g.fillRect (x, y, 50, 30);
}
public void actionPerformed (ActionEvent e)
{
if (x < 0)
{
velX = 0;
x = 0;
}
else if (x > 530)
{
velX = 0;
x = 530;
}
if (y < 0)
{
velY = 0;
y = 0;
}
else if (y > 330)
{
velY = 0;
y = 330;
}
x = x + velX;
y = y + velY;
repaint ();
}
public void keyPressed (KeyEvent e)
{
int c = e.getKeyCode ();
if (c == KeyEvent.VK_LEFT)
{
velX = -1;
velY = 0;
}
if (c == KeyEvent.VK_UP)
{
velX = 0;
velY = -1;
}
if (c == KeyEvent.VK_RIGHT)
{
velX = 1;
velY = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = 1;
}
}
public void keyTyped (KeyEvent e) {}
public void keyReleased (KeyEvent e)
{
velX = 0;
velY = 0;
}
public static void main (String arge [])
{
Tutorial t = new Tutorial ();
JFrame jf = new JFrame ();
jf.setTitle ("Tutorial");
jf.setSize (600, 400);
jf.setVisible (true);
jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
jf.add(t);
}
} // Test class

My rectangle sometimes moves when I run my java program

I should be able to move the rectangle with the arrow keys but after running the program a few times the rectangle does not move. To make the rectangle move I close Netbeans and reopen it. Then the rectangle is able to move but it stops moving after a couple tries. I want to solve this problem so I can make changes.
package project;
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.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;
//KeyListener is use with keyboard
public class main extends JPanel implements ActionListener, KeyListener
{
Timer tm = new Timer(5, this); //for animation
int x = 50, y = 50, velX =0, velY = 0;
public main()
{
tm.start(); //starts timer
addKeyListener(this); //this refearing to KeyListener
setFocusable(true); //enable KeyListener
setFocusTraversalKeysEnabled(false); //shift or tab is not use so F
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(x,y,50,50);
}
public void actionPerformed(ActionEvent e)
{
if (x<0)
{
velX = 0;
x = 0;
}
if (x>500)
{
velX = 0;
x = 500;
}
if (y<0)
{
velY = 0;
y=0;
}
if (y>300)
{
velY = 0;
y = 300;
}
x = x + velX;
y = y + velY;
repaint(); // repaint rectangle
}
public void keyPressed(KeyEvent e)
{
int c = e.getKeyCode(); //get key
if (c == KeyEvent.VK_LEFT) // VK_Left is left arrow
{
velX = -3;
velY = 0;
}
if (c == KeyEvent.VK_UP) // VK_UP is up arrow
{
velX = 0;
velY = -3; // means up
}
if (c == KeyEvent.VK_RIGHT)
{
velX = 3;
velY = 0;
}
if (c == KeyEvent.VK_DOWN)
{
velX = 0;
velY = 3;
}
}
public void keyTyped(KeyEvent e){}
public void keyReleased(KeyEvent e) //when you stop pressing
{
velX = 0;
velY = 0;
}
public static void main(String[] args)
{
main m = new main();
JFrame jf = new JFrame();
jf.setTitle("Tutorial");
jf.setSize(600,400);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(m);
}
}

Want to move my object vertically and horizontal, my code move in angles

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
#SuppressWarnings("serial")
public class Game extends JPanel {
Ball ball = new Ball(this);
Number123 num123 = new Number123(this);
public Game(){
addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
ball.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
ball.keyPressed(e);
}
});
setFocusable(true);
}
private void move() {
ball.move();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
ball.paint(g2d);
num123.paintComponent(g2d);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Two sprites");
Game game = new Game();
frame.add(game);
frame.setSize(600, 800);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
while (true) {
game.move();
game.repaint();
Thread.sleep(10);
}
}
}
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Ball implements ActionListener, KeyListener{
int x = 0;
int y = 0;
int xa = 0;
int ya = 0;
private Game game;
public Ball(Game game){
this.game= game;
}
void move(){
if (x + xa > 0 && x + xa < game.getWidth()-60)
x = x + xa;
if (y + ya > 0 && y + ya < game.getHeight()-60)
y = y + ya;
}
public void paint(Graphics2D g){
g.fillOval(x, y, 30, 30);
}
public void keyReleased(KeyEvent e) {
if (xa == 1){
xa = 1;}
if (xa == -1){
xa = -1;
}
if (ya == 1){
ya = 1;}
if (ya == -1){
ya = -1;
}
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_LEFT)
xa = -1;
if (e.getKeyCode() == KeyEvent.VK_RIGHT)
xa = 1;
if (e.getKeyCode() == KeyEvent.VK_UP)
ya = -1;
if (e.getKeyCode() == KeyEvent.VK_DOWN)
ya = 1;
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
new to java so sorry if its a simple answer.
when i run program my circle object moves in angles not vertically and horizontal.
You need to set xa to 0 when you want to move vertically, and ya to 0 when you want to move horizontally. They get initialized that way, but never get reset.

Java 2D Game dev: Multiple key input

I'm trying to get the controls working for a 2D game written in Java. However, I'm encountering an odd bug in movement. Whenever I'm trying to use the up and left controls while firing (space bar), or down and right while firing, the game is unable to detect the pressing of the space bar. Below are the relevant code excerpts:
import java.awt.Image;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.ImageIcon;
public class Player {
private String playerPath = "images/craft.png";
private int x, y, dx, dy;
private Image image;
private ArrayList missiles;
private final int CRAFT_SIZE = 20;
public Player() {
ImageIcon ii = new ImageIcon(playerPath);
image = ii.getImage();
missiles = new ArrayList();
x = 20;
y = 20;
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_SPACE) {
fire();
}
if (key == KeyEvent.VK_LEFT) {
dx = -1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = 1;
}
if (key == KeyEvent.VK_UP) {
dy = -1;
}
if (key == KeyEvent.VK_DOWN) {
dy = 1;
}
}
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;
}
if (key == KeyEvent.VK_DOWN) {
dy = 0;
}
}
public void fire() {
missiles.add(new Projectile(x + CRAFT_SIZE, y + CRAFT_SIZE/2));
}
}//end class Player
And
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 java.util.ArrayList;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Game extends JPanel implements ActionListener {
private Player player;
private Timer timer;
private int winHeight;
private int winWidth;
private final int UP = KeyEvent.VK_UP;
private final int DOWN = KeyEvent.VK_DOWN;
private final int LEFT = KeyEvent.VK_LEFT;
private final int RIGHT = KeyEvent.VK_RIGHT;
private final int SPACE = KeyEvent.VK_SPACE;
public Game(int w, int h) {
addKeyListener(new TAdapter());
setBackground(Color.BLACK);
addKeyListener(new TAdapter());
setFocusable(true);
setDoubleBuffered(true);
player = new Player();
winHeight = h;
winWidth = w;
timer = new Timer(5, this);
timer.start();
}
#Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(player.getImage(), player.getX(), player.getY(), this);
ArrayList proj = player.getMissiles();
for (Object p : proj) {
Projectile b = (Projectile) p;
g2d.drawImage(b.getImage(), b.getX(), b.getY(), this);
}
Toolkit.getDefaultToolkit().sync();
g.dispose();
}
#Override
public void actionPerformed(ActionEvent e) {
// Update projectile locations
ArrayList ms = player.getMissiles();
for (int i = 0; i < ms.size(); i++) {
Projectile p = (Projectile) ms.get(i);
if (p.getX() <= winWidth) {
p.move();
} else {
ms.remove(p);
}
}
player.move();
repaint();
}
private class TAdapter extends KeyAdapter {
#Override
public void keyReleased(KeyEvent e) {
player.keyReleased(e);
}
#Override
public void keyPressed(KeyEvent e) {
player.keyPressed(e);
}
}// end class TAdapter
}// end class Game
Whenever I'm trying to use the up and left controls while firing (space bar), or down and right while firing, the game is unable to detect the pressing of the space bar.
KeyEvents are only generated for the last key pressed. If you want to handle multiple keys being pressed at the same time then you need to:
keep track of a key that has been pressed/released
use a Swing Timer to schedule the animation.
Then whenever the timer fires you check which keys are currently pressed and the do the action for that key.

Categories