What I'm trying to do is practice some swing coding. I created a rectangle from scratch and gave it an x and y position on the frame. What I've been trying to do is use a key listener to update the x variable to move it left and right.
Here I created a class which implements an Action Listener:
public class Board extends JPanel implements ActionListener {
I added "x" and "y" variables:
int x, y;
int dx;
int HEIGHT, WIDTH;
private final int DELAY = 50;
Next are some additional functions:
public Board() {
setBackground(Color.BLACK);
setFocusable(true);
setDoubleBuffered(true);
addKeyListener(new TAdapter());
x = 15;
y = 150;
dx = 5; //This is what I want to use to update the x variable if possible.
HEIGHT = 15;
WIDTH = 15;
}
This is where I created the square with said "x" and "y" variables:
public void paint(Graphics g) {
super.paint(g);
int red = 103;
int green = 10;
int blue = 100;
Color square = new Color(red, green, blue);
g.setColor(square);
g.fillRect(x, y, WIDTH, HEIGHT);
Toolkit.getDefaultToolkit().sync();
}
Ok, now onto what I'm trying to accomplish.
I created a "move" method that will be fed into the Action Performed method and then I created a Key Adapter method that handles the Key Events:
public void move() {
x += dx;
}
public void actionPerformed(ActionEvent e) {
move();
repaint();
}
private class TAdapter extends KeyAdapter {
public void KeyPressed(KeyEvent e) {
int key = e.getKeyCode();
if (key == KeyEvent.VK_LEFT) {
dx = 1;
}
if (key == KeyEvent.VK_RIGHT) {
dx = -1;
}
}
}
Here's a screenshot of what I'm getting:
Everything manifests through another class, but all that does is initialize the various JFrame components (size, visibility, etc.) and starts the program.
When I run the program I cannot get the x variable to update. Can someone let me know what I need to add?
Thanks.