1

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

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按钮被禁用。考虑到我目前的实施,这甚至可能吗?

4

3 回答 3

6

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

于 2008-11-13T09:43:00.777 回答
1

我不知道您是要禁用该按钮还是要删除它?在您的代码中,您正在调用删除,而在您的答案中,您正在谈论禁用。您可以通过将 KeyListener 添加到 alphabetPanel 来实现此目的。因此,您可以在开始 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);
    }
});
于 2008-11-13T10:55:54.547 回答
0

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

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

于 2008-11-13T13:14:20.033 回答