1

So everything in my program works, except for the mouse and the keyboard listeners. I've got a couple actionListeners working on Jbuttons that do exactly what I'm trying to do here, but the assignment says it has to work with all three. So I would like to know why it compiles, but doesn't work. Am I doing something wrong?

panel.addKeyListener(new KeyListener() {
        @Override
        public void keyTyped(KeyEvent e) {

        }

        @Override
        public void keyPressed(KeyEvent e) {
             if(e.getKeyCode() == KeyEvent.VK_UP){
                shape.addSides();
            }
            if(e.getKeyCode() == KeyEvent.VK_DOWN){
                shape.subSides();
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {

        }

    }

    );
    panel.addMouseListener(new MouseListener(){
        @Override
        public void mouseEntered(MouseEvent e){
            if(e.getButton() == MouseEvent.BUTTON1){

                shape.addSides();
            }
            if(e.getButton() == MouseEvent.BUTTON3){

                shape.subSides();
            }

        }

        @Override
        public void mouseClicked(MouseEvent e) {

        }

        @Override
        public void mousePressed(MouseEvent e) {   
        }

        @Override
        public void mouseReleased(MouseEvent e) {
        }

        @Override
        public void mouseExited(MouseEvent e) {
        }

    }
    );

1 Answer 1

3

Regarding KeyListener: it won't work unless the listened-to component is focusable and has focus. So you will want to call setFocusable(true) and requestFocusInWindow() on your JPanel. As for the MouseListener -- something else may be taking the mouse event and preventing it from reaching your JPanel. To debug this you need to post a minimal, compilable, runnable example program.

Also regarding your MouseListener, you're checking getButton() in a mouseEntered event which makes no sense. The buttons are not involved in this type of event. Are you instead meaning to check mouseDragged(...) of a MouseMotionListener?

Sign up to request clarification or add additional context in comments.

2 Comments

+1. Another way is set keybinding on JButton's using JComponent.WHEN_IN_FOCUSED_WINDOW condition, as described in this Q&A
Completely missed the setFocusable(true) and requestFocusInWindow() in my book. That fixed he keyboard for me. As for the placement of the mouseListener, I had it where it is placed above originally. When it didn't work I did a copypasta to all 4 to hope one would work, and it didn't. When I just put it in mouseClicked() it does work. Thank you for your help. I got the project completed on time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.