I have problem with KeyListener, I've been searching solution but it should be working. Unfortunately, it doesn't and i have no idea why. When i type up arrow, nothing happens. I was reading about "Focus", but I don't know how this works, maybe you can give me some example, unnecessary to my problem.
public class Trawa extends JPanel implements KeyListener {
int wysokosc = 200;
public Trawa(){
addKeyListener(this);
setSize(200,600);
setBackground(Color.GREEN);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
Color c1 = new Color(36,217,36);
g2d.setColor(c1);
g2d.fillRect(10, wysokosc, 100, 100);
c1 = new Color(0,0,0);
g2d.setColor(c1);
g2d.fillRect(10, wysokosc, 30, 30);
g2d.fillRect(80, wysokosc, 30, 30);
c1 = new Color(252,3,0);
g2d.setColor(c1);
g2d.fillRect(40, wysokosc+60 ,30,30);
}
@Override
public void keyPressed(KeyEvent arg0) {
int key = arg0.getKeyCode();
if(key == KeyEvent.VK_UP)
wysokosc-=100;
repaint();
}
@Override
public void keyReleased(KeyEvent arg0) {
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
Here is my main class with frame. Maybe the problem is here.
public class GUI extends JFrame{
public GUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
add(new Trawa());
setLayout(new GridLayout(1,5));
pack();
setSize(1300, 600);
setLocation(40, 100);
setVisible(true);
}
public static void main(String[] args) {
new GUI();
}
}