0

I am having a checkbox and a button. I want that when i press ENTER to activate the button. It works as expected if i just press enter at run, but if i use the checkbox before, it doesn't work anymore.

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;

import javax.swing.*;
import javax.swing.plaf.LayerUI;


public class Animation{


    public Animation(){

         JFrame frame = new JFrame();
         Pane a = new Pane();
         a.addKeyListener(a);
         frame.add(a);
         //frame.setUndecorated(true);
        // frame.setOpacity(0.9f);
         frame.setVisible(true);
         frame.setSize(700, 300);
         frame.setLocationRelativeTo(null);
         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }




    public static void main(String[] args) {
        new Animation();
    }




 public class Pane extends JPanel implements KeyListener{
     JButton buton = new JButton("BUTTON!!!! ");
        JCheckBox c = new JCheckBox("Check");
        public Pane(){
     add(new JCheckBox("CHECKK"));
     add(buton);
     c.setFocusable(false);

     buton.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){
            System.out.println("Pressed!");
        }
     });

    }

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

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

        }
        public void keyPressed(KeyEvent arg0) {

                if(arg0.getKeyCosw() == KeyEvent.VK_ENTER){
                    //if(buton.isDisplayable()){
                        System.out.println("pressed");
                        //buton.doClick();
                        //return;
                        //}

                }
 }
 }
}
AXL
  • 17
  • 1
  • 6

1 Answers1

0

keyPressed is not called in this code sample. Is buton.addKeyListener( this ); missing?

If you use checkbox, it receives a focus. You can call setFocusable( false ) on that checkbox. So the only focused component will be the button. And it will always receive key events.

Otherwise, you can add key listener to checkbox too.

Also, take a llok at this answer to find out how to set a global key listener (if you don't want to deny focusing components or don't want to add a key listener to every component).

Community
  • 1
  • 1
Qualtagh
  • 721
  • 6
  • 15
  • It wasn't called because there was no `addKeyListener`. Now it's present. Look: the key event is caught on the focused component. You have added the listener to the panel and it's never focused. So you have three ways described in my answer to solve the problem: 1. deny focusing components except that one which listens for key events, 2. add key listener to every component, 3. add global key listener. – Qualtagh Feb 12 '15 at 03:49