2008-11-13 77 views
1

我创建了26 JButton以匿名actionListener标记为字母表中的每个字母。从另一个匿名类访问匿名类中的“无名”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,那么按钮被禁用。鉴于我目前的实施,这甚至有可能吗?

回答

6

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

+0

甚至将它们存储在由字符键入一个地图,这样你就可以用字符查找一个JButton实例。 – 2008-11-13 09:59:30

1

我不知道是否要禁用该按钮或者是否要删除它?在你的代码中,你打电话去除,在你的回答中你正在谈论禁用。您可以通过在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); 
    } 
}); 
0

您也可以通过元器件迭代,比较的getText( )到按下的键。

正如别人所说,匿名类也可以访问外部类的成员以及当地决赛