键绑定中的焦点导航 [英] Focus navigation in keyBinding

查看:95
本文介绍了键绑定中的焦点导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的表单中,当我按下键盘上的ENTER按钮时,应该调用okAction()方法(并完美地调用).

In my form, when i press ENTER button in my keyboard, the okAction() method should be invoke (and invoke perfectly).

我的问题是处于焦点状态,当我填充文本字段,然后按ENTER按钮时,未调用okAction(),因为焦点位于第二个文本字段(而不是面板上).

My problem is in focus state, When i fill the text fields and then press the ENTER button, the okAction() didn't invoked, because the focus is on the second text field (not on the panel).

如何解决此问题?

public class T3 extends JFrame implements ActionListener {

JButton cancelBtn, okBtn;
JLabel fNameLbl, lNameLbl, tempBtn;
JTextField fNameTf, lNameTf;

public T3() {
    add(createForm(), BorderLayout.NORTH);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setSize(400, 500);
    setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new T3();
        }
    });
}

public JPanel createForm() {
    JPanel panel = new JPanel();
    panel.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "Button");
    panel.getActionMap().put("Button", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            okAction();
        }
    });

    okBtn = new JButton("Ok");
    okBtn.addActionListener(this);
    cancelBtn = new JButton("Cancel");
    tempBtn = new JLabel();
    fNameLbl = new JLabel("First Name");
    lNameLbl = new JLabel("Last Name");
    fNameTf = new JTextField(10);
    fNameTf.setName("FnTF");
    lNameTf = new JTextField(10);
    lNameTf.setName("LnTF");

    panel.add(fNameLbl);
    panel.add(fNameTf);
    panel.add(lNameLbl);
    panel.add(lNameTf);
    panel.add(okBtn);
    panel.add(cancelBtn);
    panel.add(tempBtn);

    panel.setLayout(new SpringLayout());
    SpringUtilities.makeCompactGrid(panel, 3, 2, 50, 10, 80, 60);
    return panel;
}

private void okAction() {
    if (fNameTf.getText().trim().length() != 0 && lNameTf.getText().trim().length() != 0) {
        System.out.println("Data saved");
    } else System.out.println("invalid data");
}

@Override
public void actionPerformed(ActionEvent e) {
    if (e.getSource() == okBtn) {
        okAction();
    }
}
}

推荐答案

为GUI的JRootPane声明默认按钮:

Declare a default button for your GUI's JRootPane:

public T3() {

  //!! ..... etc...

  setVisible(true);
  getRootPane().setDefaultButton(okBtn);
}

实际上设置了默认按钮,我看不到您需要使用按键绑定.

In fact with a default button set, I don't see that you need to use key bindings.

这篇关于键绑定中的焦点导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆