Search code examples
javaswingjframejbuttonkeylistener

How can the Mouselistener be used ? to move buttons?


I am currently working on a small boardgame. I have to place "objects" on a Button array. I thought of placing the objects are 1*1 1*2 etc,They are represented by disabled buttons. Is there any way that i can move the spawned Disabled Buttons with Keylisteners of my keyboard, since i cant get it to work

public GuiP1() {
    super();
    Panel.setLayout(null);
    this.add(Panel);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setTitle("BattleshipsP1");
    this.setSize(640, 1000);
    this.setVisible(false);
    this.addKeyListener(new KeyListener() {
        public void keyPressed(KeyEvent arg0) {
        }
        public void keyReleased(KeyEvent arg0) {

            if (arg0.getKeyCode() == KeyEvent.VK_RIGHT) {
                System.out.println("VK_RIGHT");
            } else if (arg0.getKeyCode() == KeyEvent.VK_LEFT) {
                System.out.println("VK_LEFT");
            } else if (arg0.getKeyCode() == KeyEvent.VK_UP) {
                System.out.println("VK_UP");
            } else if (arg0.getKeyCode() == KeyEvent.VK_DOWN) {
                System.out.println("VK_DOWN");
            }
        }
        public void keyTyped(KeyEvent arg0) {
        }
    });
    Grid();
    this.setVisible(true);
}

It wont listen for keys beeing pressed

Thank you JFluX


Solution

  • Your KeyListeners are not working because the listened to component must be focusable and have focus for them to work. A kludge solution is to force the listened to component to have focus by

    • making the listened to component focusable via setFocusable(true)
    • By giving it the focus via requestFocusInWindow()
    • and by making added components non-focusable by calling setFocusable(false) on them.

    A much better solution is to use Key Bindings which isn't tied as closely to component focus.