在匿名类中引用事物的一种方法是使用
final关键字:
public static void main(String[] args) { final Object thingIWantToUse = "Hello"; JButton button = new JButton("Click"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { System.out.println(thingIWantToUse); } }); Jframe frame = new Jframe(); frame.setLayout(new FlowLayout()); frame.add(button); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); }或者,您可以访问封闭类型的成员(变量或方法):
public class ActionListenerDemo2 { private final Jframe frame = new Jframe(); private Object thingIWantToUse = "Hello"; public ActionListenerDemo2() { JButton button = new JButton("Click"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { thingIWantToUse = "Goodbye"; System.out.println(thingIWantToUse); } }); frame.setLayout(new FlowLayout()); frame.add(button); frame.setDefaultCloseOperation(Jframe.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } public static void main(String[] args) { new ActionListenerDemo2().frame.setVisible(true); }}


