Java 访问一个";“无名”;匿名类中的Jbutton是否来自另一个匿名类?

Java 访问一个";“无名”;匿名类中的Jbutton是否来自另一个匿名类?,java,swing,actionlistener,keylistener,Java,Swing,Actionlistener,Keylistener,我在一个匿名的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 ()

我在一个匿名的
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 + "");
} 
for(int i=65;i<91;i++){
最终字符c=(字符)i;
最终按钮=新按钮(“+c”);
添加(按钮);
button.addActionListener(
新建ActionListener(){
已执行的公共无效操作(操作事件e){
字母猜测(c);
移除(按钮);
}
});
//设置按钮的名称
按钮。设置名称(c+“”);
} 

现在我有了一个匿名的
keylister
类,我想根据键盘上按下的字母禁用按钮。因此,如果用户按下A,则A按钮被禁用。考虑到我当前的实现,这可能吗?

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

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

我不知道您是要禁用按钮还是要删除它?在您的代码中,您正在调用remove,在您的回答中,您正在谈论禁用。您可以通过向alphabetPanel添加一个KeyListener来实现这一点。因此,您可以在开始for循环之前添加以下内容:

InputMap iMap = alphabetPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap aMap = alphabetPanel.getActionMap();
与添加到JButton的ActionListener不同,请调用以下命令:

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);
    }
});

我不知道你是想禁用按钮还是想删除它?在您的代码中,您正在调用remove,在您的回答中,您正在谈论禁用。您可以通过向alphabetPanel添加一个KeyListener来实现这一点。因此,您可以在开始for循环之前添加以下内容:

InputMap iMap = alphabetPanel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap aMap = alphabetPanel.getActionMap();
与添加到JButton的ActionListener不同,请调用以下命令:

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()与按下的键进行比较


正如其他人提到的,匿名类还可以访问外部类的成员以及本地类的成员。您还可以通过比较getText()和按下的键来迭代组件


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

,甚至可以将它们存储在按字符键控的映射中,这样您就可以按字符查找JButton实例。或者甚至可以将它们存储在按字符键控的映射中,这样您就可以按字符查找JButton实例。