Key listener not detecting key presses? - java

I am trying to make my picture move based on the arrow keys being pressed but the key listener is not detecting any key presses. I attached the code for the panel which i add to a frame in a driver.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
public class RacePanel extends JPanel
{
//variables
private ImageIcon backGround = new ImageIcon("images/back.png");
private Penguin p;
private ImageIcon icon1 = new ImageIcon("images/PenguinR.png");
private ImageIcon icon2 = new ImageIcon("images/PenguinL.png");
private int x = 10;
//move left and right methods
public void moveLeft(Penguin x)
{
x.setImageIcon(icon2);
x.setX(x.getX() - 5);
}
public void moveRight(Penguin x)
{
x.setImageIcon(icon1);
x.setX(x.getX() + 5);
}
public RacePanel()
{
JPanel RacePanel = new JPanel();
super.addKeyListener(new Key());
setFocusable(true);
p = new Penguin();
Timer t = new Timer(50, new Listener());
t.start();
}
private class Key implements KeyListener
{
public Key()
{
addKeyListener(this);
}
public void keyTyped(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_RIGHT)
{
moveRight(p);
}
if(e.getKeyCode() == KeyEvent.VK_LEFT)
{
moveLeft(p);
}
if(e.getKeyCode() == KeyEvent.VK_UP)
{
System.out.println("i am listening");
}
repaint();
}
public void keyReleased(KeyEvent e)
{
}
}
//graphics
public void paintComponent(Graphics g)
{
g.drawImage(backGround.getImage(),0,0,800,600,null);
g.drawImage(p.getImageIcon().getImage(),p.getX(),p.getY(),50,100,null);
}
//action listener .05 second loop
private class Listener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
repaint();
}
}
}
I know that it is not recognizing key pressed because i added a line of code to print "i am listening" if the up arrow is pressed and nothing prints.
I also know the issue is not because of the timer cause i tested it by adding the moveRight method to the actionPerformed method.

Related

KeyListener not working when changing card in Java GUI

Below is a simplified version of my code. The menu panel just has a start button and the game panel is just a black screen with a square that's supposed to move when the arrow keys are pressed. So when I click the button in the menu panel to start the game, the graphics load up fine, but the key listener doesn't work at all. This seems to only be a problem when there are multiple panels involved, or when I switch between them. I'm a complete beginner, so any advice would be really helpful.
Main class
import javax.swing.JFrame;
public class Main {
public static void main(String[] args) {
MyFrame frame= new MyFrame();
frame.setSize(1000,1000);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
MyFrame Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrame extends JFrame implements ActionListener{
CardLayout card;
JButton b1;
Container c;
MyPanel game;
JPanel menu;
public MyFrame(){
c=getContentPane();
card=new CardLayout();
c.setLayout(card);
game = new MyPanel();
menu = new JPanel();
b1=new JButton("Start");
b1.addActionListener(this);
c.add("p", menu);
menu.add("a",b1);
c.add("d", game);
}
public void actionPerformed(ActionEvent e) {
card.show(c, "d");
}
}
MyPanel class
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.*;
public class MyPanel extends JPanel implements ActionListener, MouseListener, MouseMotionListener, KeyListener{
Timer myTimer;
int x = 0;
int y = 0;
int xVel, yVel;
public MyPanel() {
myTimer = new Timer(50, this);
myTimer.start();
this.addKeyListener(this);
this.setFocusable(true);
this.requestFocusInWindow();
this.addMouseListener(this);
this.addMouseMotionListener(this);
}
public void startTimer() {
myTimer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(Color.BLACK);
g.setColor(Color.CYAN);
g.drawRect(x, y, 100, 100);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==myTimer) {
repaint();
x += xVel;
y += yVel;
}
}
public void mouseDragged(MouseEvent e) {}
public void mouseMoved(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
if(key== KeyEvent.VK_UP) {
up();
}
if(key== KeyEvent.VK_DOWN) {
down();
}
if(key== KeyEvent.VK_RIGHT) {
right();
}
if(key== KeyEvent.VK_LEFT) {
left();
}
}
public void keyReleased(KeyEvent e) {
xVel = 0;
yVel = 0;
}
public void up() {
xVel = 0;
yVel = -5;
}
public void down() {
xVel = 0;
yVel = 5;
}
public void right() {
xVel = 5;
yVel = 0;
}
public void left() {
xVel = -5;
yVel = 0;
}
}
A simple fix is to add game.requestFocusInWindow(); in your actionPerformed method of your MyFrame class.

Java KeyListener not responding at all

I am trying to make the game pong but i am having trouble with the KeyListener not working. What is wrong with the KeyListener? It is just not working and everything i look up doesn't work for me. It seems to work for other people.
Am i using it in the wrong place?
I hope anyone can help me with this.
Thanks in advance!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class Paneel extends JPanel
{
private int height, width;
private boolean moveLeft, moveRight, moveUp, moveDown, playerMoveLeft, playerMoveRight, computerMoveLeft, computerMoveRight;
private Timer timer;
private Ball ball;
private Paddle player, computer;
public Paneel()
{
ball = new Ball(994, 772);
player = new Paddle(1, 994, 722);
computer = new Paddle(2, 944, 722);
TimerHandler timerHandler = new TimerHandler();
timer = new Timer(20, timerHandler);
timer.start();
this.addKeyListener(new KeyListener() {
#Override
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT) playerMoveLeft = true;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) playerMoveRight = true;
}
#Override
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT) playerMoveLeft = false;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) playerMoveRight = false;
}
#Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
});
}
public void paintComponent(Graphics pen)
{
super.paintComponent(pen);
ball.drawBall(pen);
player.drawPaddle(pen);
computer.drawPaddle(pen);
}
public void movePlayer()
{
if (playerMoveRight == true) player.moveDown();
else if (playerMoveLeft == true) player.moveUp();
}
public void moveComputer()
{
}
public void resetBall()
{
}
public void resetPlayer()
{
}
public void resetComputer()
{
}
class TimerHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
movePlayer();
repaint();
}
}
}
set focus on your panel by requestFocus(); i hop that will solve the problem

Java key event not working

Hello i am trying to make the game pong. Now i am trying to move the paddle with my keyboard but it is not responding at all. Can anyone tell me what i am missing here? I can't figure it out what it is i am doing wrong.
The paddle is moving when i set the condition in the check to false so there is not a problem in moving it. Just getting the keyEvent to work.
What am i missing in the keyEvent?
Thanks in advance!
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.*;
public class Paneel extends JPanel
{
private int height, width;
private boolean moveLeft, moveRight, moveUp, moveDown, playerMoveLeft,
playerMoveRight, computerMoveLeft, computerMoveRight = false;
private Timer timer;
private Ball ball;
private Paddle player, computer;
public Paneel()
{
ball = new Ball(994, 772);
player = new Paddle(1, 994, 722);
computer = new Paddle(2, 944, 722);
TimerHandler timerHandler = new TimerHandler();
timer = new Timer(20, timerHandler);
timer.start();
}
public void paintComponent(Graphics pen)
{
super.paintComponent(pen);
ball.drawBall(pen);
player.drawPaddle(pen);
computer.drawPaddle(pen);
pen.drawString("" + getHeight() + " " + getWidth(), 50, 50);
}
public void keyPressed(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT) playerMoveLeft = true;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) playerMoveRight =
true;
}
public void keyReleased(KeyEvent e)
{
if (e.getKeyCode() == KeyEvent.VK_LEFT) playerMoveLeft = false;
else if (e.getKeyCode() == KeyEvent.VK_RIGHT) playerMoveRight =
false;
}
public void movePlayer()
{
if (playerMoveRight == true) player.moveDown();
else if (playerMoveLeft == true) player.moveUp();
}
public void moveComputer()
{
}
public void resetBall()
{
}
public void resetPlayer()
{
}
public void resetComputer()
{
}
class TimerHandler implements ActionListener
{
public void actionPerformed(ActionEvent e) {
movePlayer();
repaint();
}
}
}

How do I move an object using Keyboard Control? [duplicate]

I have written a sample code using KeyListener in Java,
I have created a JPanel, then set its focusable to true, I have created a KeyListener, requested a focus and then added the KeyListener to my panel. But the methods for the keyListener are never called. It seems although I have requested focus, it does not focus.
Can anyone help?
listener = new KeyLis();
this.setFocusable(true);
this.requestFocus();
this.addKeyListener(listener);
class KeyLis implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
currentver += 5;
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT : if(horizontalyInBounds()) currentPos-= 5;
break;
case KeyEvent.VK_RIGHT: if(horizontalyInBounds()) currentPos+= 5;
break;
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
}
}
If any runnable code should be needed:
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class test extends JFrame {
private AreaOfGame areaOfGame;
public test()
{
super("");
setVisible(true);
this.setBackground(Color.darkGray);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
setLayout(null);
setBounds(200, 10, 400, 700);
areaOfGame = new AreaOfGame();
this.add(areaOfGame);
startGame();
}
public int generateNext()
{
Random r = new Random();
int n = r.nextInt(7);
return n;
}
public void startGame()
{
while(!areaOfGame.GameOver())
{
areaOfGame.startGame(generateNext());
}
}
public static void main(String[] args) {
new MainFrame();
}
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JPanel;
public class AreaOfGame extends JPanel {
private static final int rightside = 370;
private int bottom;
private int top;
private int currentPos;
private int currentver;
private KeyLis listener;
public AreaOfGame()
{
super();
bottom = 650;
top = 50;
setLayout(null);
setBounds(20, 50, 350, 600);
setVisible(true);
this.setBackground(Color.lightGray);
listener = new KeyLis();
this.setFocusable(true);
if(this.requestFocus(true))
System.out.println("true");;
this.addKeyListener(listener);
currentPos = 150;
currentver=0;
}
public void startGame(int n)
{
while(verticallyInBound()){
System.out.println("anything");
}
}
public boolean verticallyInBound()
{
if(currentPos<= bottom -50)
return true;
return false;
}
public boolean GameOver()
{
if(top>= bottom){
System.out.println("game over");
return true;
}
else return false;
}
public boolean horizontalyInBounds()
{
if(currentPos<=rightside && currentPos>= 20)
return true;
else return false;
}
class KeyLis implements KeyListener{
#Override
public void keyPressed(KeyEvent e) {
System.out.println("called");
currentver += 5;
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT : if(horizontalyInBounds()) currentPos-= 5; break;
case KeyEvent.VK_RIGHT: if(horizontalyInBounds()) currentPos+= 5; break;
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("called 3");
}
}
}
I'll bet that you're requesting focus before the JPanel has been rendered (before the top level window has either had pack() or setVisible(true) called), and if so, this won't work. Focus request will only be possibly granted after components have been rendered. Have you checked what your call to requestFocus() has returned? It must return true for your call to have any chance for a success. Also it's better to use requestFocusInWindow() rather than requestFocus().
But more importantly, you shouldn't be using KeyListeners for this but rather key bindings, a higher level concept that Swing itself uses to respond to key presses.
Edit
An example of an SSCCE:
import java.awt.Dimension;
import java.awt.event.*;
import javax.swing.*;
public class TestKeyListener extends JPanel {
private KeyLis listener;
public TestKeyListener() {
add(new JButton("Foo")); // something to draw off focus
listener = new KeyLis();
this.setFocusable(true);
this.requestFocus();
this.addKeyListener(listener);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
private class KeyLis extends KeyAdapter {
#Override
public void keyPressed(KeyEvent e) {
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
System.out.println("VK_LEFT pressed");
break;
case KeyEvent.VK_RIGHT:
System.out.println("VK_RIGHT pressed");
break;
}
}
}
private static void createAndShowGui() {
TestKeyListener mainPanel = new TestKeyListener();
JFrame frame = new JFrame("TestKeyListener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit 2
And the equivalent SSCCE using Key Bindings:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class TestKeyBindings extends JPanel {
public TestKeyBindings() {
add(new JButton("Foo")); // something to draw off focus
setKeyBindings();
}
private void setKeyBindings() {
ActionMap actionMap = getActionMap();
int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
InputMap inputMap = getInputMap(condition );
String vkLeft = "VK_LEFT";
String vkRight = "VK_RIGHT";
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), vkLeft);
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), vkRight);
actionMap.put(vkLeft, new KeyAction(vkLeft));
actionMap.put(vkRight, new KeyAction(vkRight));
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 200);
}
private class KeyAction extends AbstractAction {
public KeyAction(String actionCommand) {
putValue(ACTION_COMMAND_KEY, actionCommand);
}
#Override
public void actionPerformed(ActionEvent actionEvt) {
System.out.println(actionEvt.getActionCommand() + " pressed");
}
}
private static void createAndShowGui() {
TestKeyBindings mainPanel = new TestKeyBindings();
JFrame frame = new JFrame("TestKeyListener");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Edit 3
Regarding your recent SSCCE, your while (true) loops are blocking your Swing event thread and may prevent user interaction or painting from happening. Better to use a Swing Timer rather than while (true). For example:
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class BbbTest extends JFrame {
private AreaOfGame areaOfGame;
public BbbTest() {
super("");
// setVisible(true);
this.setBackground(Color.darkGray);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
setLayout(null);
setBounds(200, 10, 400, 700);
areaOfGame = new AreaOfGame();
this.add(areaOfGame);
setVisible(true);
startGame();
}
public int generateNext() {
Random r = new Random();
int n = r.nextInt(7);
return n;
}
public void startGame() {
// while (!areaOfGame.GameOver()) {
// areaOfGame.startGame(generateNext());
// }
areaOfGame.startGame(generateNext());
}
public static void main(String[] args) {
new BbbTest();
}
class AreaOfGame extends JPanel {
private static final int rightside = 370;
private int bottom;
private int top;
private int currentPos;
private int currentver;
private KeyLis listener;
public AreaOfGame() {
super();
bottom = 650;
top = 50;
setLayout(null);
setBounds(20, 50, 350, 600);
setVisible(true);
this.setBackground(Color.lightGray);
listener = new KeyLis();
this.setFocusable(true);
if (this.requestFocus(true))
System.out.println("true");
;
this.addKeyListener(listener);
currentPos = 150;
currentver = 0;
}
public void startGame(int n) {
// while (verticallyInBound()) {
// System.out.println("anything");
// }
int timeDelay = 50; // msecs delay
new Timer(timeDelay , new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("anything");
}
}).start();
}
public boolean verticallyInBound() {
if (currentPos <= bottom - 50)
return true;
return false;
}
public boolean GameOver() {
if (top >= bottom) {
System.out.println("game over");
return true;
}
else
return false;
}
public boolean horizontalyInBounds() {
if (currentPos <= rightside && currentPos >= 20)
return true;
else
return false;
}
class KeyLis implements KeyListener {
#Override
public void keyPressed(KeyEvent e) {
System.out.println("called");
currentver += 5;
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT:
if (horizontalyInBounds())
currentPos -= 5;
break;
case KeyEvent.VK_RIGHT:
if (horizontalyInBounds())
currentPos += 5;
break;
}
repaint();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("called 3");
}
}
}
}
It's possible to use the "TAB" button to switch between the buttons and the key listener.
I have a program with one button that after I press it, the key listener does not work.
I realized that if you press the "TAB" button, the "Attention" or "focus" of the program returns to the key listener.
maybe this will help: http://docstore.mik.ua/orelly/java-ent/jfc/ch03_08.htm

Adding a keylistener to main() not working

I'm making a game in Java where a ball moves forward constantly with no user control, but the user can control the vertical movement of the ball, using the up and down arrow keys, however I'm stuck on adding the keylistener class/whatever it is to my JFrame, through my main method. Basically, I do add(keylistener_class/method), and Java (quite rightly), complains that my class or method is not a component. My question, then, is how AM I supposed to add the keylistener into my Jframe?
Cheers,
Matt
Code:
package org.ultraluminous.vertiball;
import java.awt.Color;
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;
public class Game extends JPanel{
static int x = 0;
static int y = 0;
static int ys = 0;
private static void shift(){
x+=1;
y+=ys;
}
public static void event(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_UP){
ys = 1;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN){
ys = -1;
}
}
public class key{
public void Listen() {
KeyListener listener = new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
}
#Override
public void keyReleased(KeyEvent e) {
}
};
addKeyListener(listener);
setFocusable(true);
}
}
#Override
public void paint(Graphics g){
super.paint(g);
Graphics2D Graph = (Graphics2D) g;
Graph.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Graph.setColor(Color.BLUE);
Graph.drawOval(x, y, 50, 50);
Graph.fillOval(x, y, 50, 50);
}
public static void main (String[] args){
JFrame Win = new JFrame("Pong");
Game game = new Game();
Win.add(new Game());
//Win.add... add what? I need to add the key listener here
//but seem to be unable to.
Win.setResizable(false);
Win.setSize(900, 600);
Win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Win.setVisible(true);
while (true) {
shift();
Win.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
I got it to work by adding the KeyListener to your JFrame. Alternatively you could create a separate class for the KeyListener and add it that way (instead of using an anonymous inner class). Here is what I added:
public static void main (String[] args){
JFrame Win = new JFrame("Pong");
Game game = new Game();
Win.add(new Game());
Win.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_UP){
ys = -1;
}
if (e.getKeyCode() == KeyEvent.VK_DOWN){
ys = 1;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
Win.setResizable(false);
Win.setSize(900, 600);
Win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Win.setVisible(true);
while (true) {
shift();
Win.repaint();
try {
Thread.sleep(10);
} catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
You can add KeyListener to your JPanel by this way:
addKeyListener(new KeyListener(){
...//all the methods.
});
Alternatively, you can use KeyAdpater, if do not use all the methods.
addKeyListener(new KeyAdapter(){
...//Only the methods you want.
});

Categories

Resources