I have a specialized frame class and a specialized panel class. I have a keylistener setup to listen for key presses of the “right” key (->)and then I call repaint but nothing happens when I press the “right” key. I believe my keylistener is done properly so I think it must be the way I call repaint(); Let me know how to fix this please.
Edit* I would like to add that I made x and y in CircleFrame static because I couldn’t find a way to call the incX() and incY() methods I had written. This was because, originally, the creation of the panel was done in the constructor for CircleBox. I took that out and put it in main in order to have a way to call repaint() for the panel but that didn’t work. I feel like theres some vital step im missing here.
package circlebox;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.Random;
public class CircleBox extends JFrame implements KeyListener {
CircleBox() {
}
public void keyPressed(KeyEvent e) {
int location = e.getKeyLocation();
if(location == KeyEvent.KEY_LOCATION_NUMPAD) {
CircleFrame.y += 1;
repaint();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public static void main(String[] args) {
CircleBox frame = new CircleBox();
frame.setSize(400,400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
CircleFrame frame2 = new CircleFrame();
frame.setLayout(new GridLayout(1,1));
frame.add(frame2);
frame.setVisible(true);
}
}
class CircleFrame extends JPanel {
static int x = 20;
static int y = 20;
int radius = 20;
CircleFrame() {
setSize(400,400);
}
@Override
protected void paintComponent(Graphics g) {
g.drawOval(x,y,radius,radius);
}
public void incX(int inc) {
x += inc;
}
public void incY(int inc) {
y += inc;
}
public int checkCollisions() {
if(x <= 0) {
return 0;
}
else if(y <= 0) {
return 1;
}
else if(x >= 400) {
return 2;
}
else if(y >= 400) {
return 3;
}
else {
return -1;
}
}
}
Your repaint is working just fine. The problem is with the key listener.
You first need to actually register your key listener. So, add this line in the
CircleBoxconstructor:Then, you must handle the
keyPressedcorrectly: