【问题标题】:Accessing a "nameless" Jbutton in an anonymous class from another anonymous class?从另一个匿名类访问匿名类中的“无名”Jbutton?
【发布时间】:2008-11-13 09:38:28
【问题描述】:

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

【问题讨论】:

    标签: java swing actionlistener keylistener


    【解决方案1】:

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

    【讨论】:

    • 或者甚至将它们存储在以字符为键的 Map 中,这样您就可以按字符查找 JButton 实例。
    【解决方案2】:

    我不知道您是要禁用该按钮还是要删除它?在您的代码中,您正在调用删除,而在您的答案中,您正在谈论禁用。您可以通过将 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);
        }
    });
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-11-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多