Reputation:
I have this code the green square is meant to move but it doesn't I have done everything right. its just the key listen doesn't seem to be responding. I think there's a error around
addKeyListener(this); in the paintComponent in my Graphics class can you please help and tell me how to fix it and what's wrong.
my Main class
import javax.swing.JFrame;
public class Main {
static int v = 50;
static int t = 1;
public static void main(String[] args) {
JFrame frame = new JFrame("window");
frame.setVisible(true);
frame.setSize(400,200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Graphics object = new Graphics();
frame.add(object);
while (v > t){
object.Drawing();
}
}
}
my Graphics class
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;
public class Graphics extends JPanel implements KeyListener {
int x = 0, y= 0, xx = 100, yy = 0, ltyx = 0, ltyyxx = 0, px = 0, py = 0;
public void Drawing(){
repaint();
}
public void paintComponent (java.awt.Graphics g){
super.paintComponent (g);
addKeyListener(this);
setBackground(Color.WHITE);
g.setColor(Color.GREEN);
g.fillRect(px, py, 25, 25);
g.setColor(Color.BLUE);
g.fillRect(x, y, 50, 50);
g.setColor(Color.RED);
g.fillRect(xx, yy, 50, 50);
g.drawString("times looped around screen Blue : " + ltyx , 10, 10);
g.drawString("Red : " + ltyyxx , 170, 20);
x++;
xx++;
if (x > 400){
x = 0;
y += 50;
}
if (xx > 400){
xx = 0;
yy += 50;
}
if (y > 200){
y = 0;
ltyx++;
}
if (yy > 200){
yy = 0;
ltyyxx++;
}
}
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:{
px++;
break;
}
case KeyEvent.VK_LEFT:{
px--;
break;
}
case KeyEvent.VK_UP:{
py++;
break;
}
case KeyEvent.VK_DOWN:{
py--;
break;
}
}
}
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()){
case KeyEvent.VK_RIGHT:{
px = 0;
break;
}
case KeyEvent.VK_LEFT:{
px = 0;
break;
}
case KeyEvent.VK_UP:{
py = 0;
break;
}
case KeyEvent.VK_DOWN:{
py = 0;
break;
}
}
}
public void keyTyped(KeyEvent e) {
}
}
Upvotes: 1
Views: 2459
Reputation: 50021
In user interfaces there is the concept of 'focus'. Only the component currently holding the focus directly receives key events. This is how for example, when typing, one text box on screen responds and not any other.
After frame.add(object);
, add:
object.setFocusable(true);
object.requestFocusInWindow();
Also, the addKeyListener(this);
call is in quite the wrong place. It will add another key listener every time it paints the component. It should be called only once, ideally in the constructor of the panel.
Upvotes: 2