public class Main {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Character c = new Character();
frame.add(c);
frame.setSize(600, 600);
frame.setTitle("Keyboard control");
frame.setResizable(false);
frame.setVisible(true);
}
}
character class
public class Character extends JPanel implements KeyListener{
int posx = 0, posy = 0;
public void movementX(int i) {
posx+=i;
}
public void movementY(int i) {
posy+=i;
}
public void paint() {
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
this.setBackground(new Color(0, 0, 0));
g.setColor(new Color(0, 0, 255));
g.fillRoundRect(posx, posy, 50, 50, 4, 4);
}
public void keyPressed(KeyEvent e) {
movementX(10);
paint();
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
}
\$\begingroup\$
\$\endgroup\$
1
-
2\$\begingroup\$ What have you tried? \$\endgroup\$– Maximus MinimusCommented May 19, 2018 at 21:40
Add a comment
|
1 Answer
\$\begingroup\$
\$\endgroup\$
well, simple you are implementing KeyListener but you are never attaching that to the panel, also you must focus your component to be able to listen for events, here you can have a more explained response: