Pergunta

So this is my code:

public void keyPressed(KeyEvent ke){
    int keyID = ke.getKeyCode();
    Object o = ke.getSource();

    if (keyID == KeyEvent.VK_ENTER){
        if(o.equals(GUI.btnOK)){
            //Do something
        }
    }}}

Ok so what this does is //Do something, when JButton called btnOK is accessed through key ENTER.

The question is: How do I place the o.equals(GUI.btnOK) to get triggered by enter when whatever element of the main panel is pressed?

It has few things and btnOK is one of them. My main panel is:

pnlMain= new JPanel(null); 

I have tried:

if (keyID == KeyEvent.VK_ENTER){
            if(o.equals(GUI.pnlMain)){
                //Do something
            }
        }

But it doesn't seem to work, despite the fact that I did add the event to the main panel.

EXAMPLE:

if (keyID== KeyEvent.VK_ESCAPE){
if(o.equals(GUI.txtLogin) || o.equals(GUI.pwfPWD) || o.equals(GUI.btnOK)){
  //Do this
  igu.setVisible(false);
  igu.dispose();
  System.exit(0); }}

In stead of placing all the buttons possible to get triggered by ESCAPE in the if(o.equals(whatever)|| etc... I want it to be available (the escape button pressed) for whenever the program is opened wherever the focus is.

Foi útil?

Solução

May be you are looking for something like this:

//You can bind key to JComponent, So whenever you press ENTER on 'JComponentit does desired operation say Transfer Focus to nextJComponent`, like:

jComponent.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "TransferFocus");
jComponent.getActionMap().put("TransferFocus", action);

//You can bind key to JButton, So whenever you press ENTER on 'JButtonit does desired operation say Click theJButton`, like:

jButton.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "DoClick");
jButton.getActionMap().put("DoClick", action);

//action

AbstractAction action = new AbstractAction() {
    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource() instanceof JButton){
        JButton button = (JButton) e.getSource();
        button.doClick();        
        } else if(e.getSource() instanceof JComponent){
            JComponent component = (JComponent) e.getSource();
            component.transferFocus();
        }
    }
    };
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top