0

I am trying to create a GUI (using Applet) the user enters keyboard input (using KeyListner) and read the data from a different class. The problem is that the ArrayList (which holds the data) always appears as empty

I have tried to make the ArrayList volatile, create a copy and to put the copy in a synchronized block.

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.List;
import java.awt.Rectangle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;

public class Listen extends Applet implements KeyListener {

private static final long serialVersionUID = 1L;
private static ArrayList<Integer> keysDown = new ArrayList<Integer>();

public void init() {
    this.addKeyListener(this);
}

@Override
public void keyPressed(KeyEvent e) {
    if(!keysDown.contains(e.getKeyCode())) {
        keysDown.add(new Integer(e.getKeyCode()));
    }
}
@Override
public void keyReleased(KeyEvent e) {
    keysDown.remove(new Integer(e.getKeyCode()));
}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

public static ArrayList<Integer> getKeys() {
    ArrayList<Integer> keysDownCopy;
    synchronized (keysDown) {
        keysDownCopy = new ArrayList<Integer>(keysDown);
        System.out.println(keysDownCopy);
    }
    return keysDownCopy;
}
}

It is called from a different class:

public class Controler{
    public static void main(String[] args) {
        while(true) {
           Listen.getKeys();
       }
   }
}

The ArrayList supposed to show all of the IDs of the pressed keys but shown as just empty ( [] ).

TheZadok42
  • 147
  • 1
  • 9

0 Answers0