我在匿名 actionListener 中创建了26 JButton ,标记为字母表中的每个字母。

for (int i = 65; i < 91; i++){
    final char c = (char)i;
    final JButton button = new JButton("" + c);
    alphabetPanel.add(button);
    button.addActionListener(
        new ActionListener () {
            public void actionPerformed(ActionEvent e) {
                letterGuessed( c );
                alphabetPanel.remove(button);
            }
        });
        // set the name of the button
        button.setName(c + "");
} 

现在我有一个匿名的 keyListener 类,我希望根据键盘上按下的字母禁用按钮。因此,如果用户按下A,则禁用 A 按钮。鉴于我目前的实施情况,这甚至可能吗?

有帮助吗?

解决方案

难道你不能简单地在类级别声明一个包含26个JButton对象的数组,这样两个侦听器都可以访问它们吗?我相信匿名内部类可以访问类变量以及最终变量。

其他提示

我不知道您是要禁用该按钮还是要删除它?在您的代码中,您正在调用删除,在您的回答中,您正在谈论禁用。您可以通过向alphabetPanel添加KeyListener来实现此目的。所以你可以在开始for循环之前添加它:

InputMap iMap = alphabetPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap aMap = alphabetPanel.getActionMap();

而不是你的ActionListener添加到JButton调用这个:

iMap.put(KeyStroke.getKeyStroke(c), "remove"+c);
aMap.put("remove"+c, new AbstractAction(){
    public void actionPerformed(ActionEvent e) {
        // if you want to remove the button use the following two lines
        alphabetPanel.remove(button);
        alphabetPanel.revalidate();
        // if you just want to disable the button use the following line
        button.setEnabled(false);
    }
});

您还可以遍历组件,将getText()与按下的键进行比较。

正如其他人提到的,匿名类也可以访问外部类的成员以及本地决赛

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top