Java 使用JButton对象的嵌套ActionListener类获取错误?
这是我第一次尝试使用动作侦听器和事件处理。我正在尝试创建一个简单的GUI,它有3个按钮:Java 使用JButton对象的嵌套ActionListener类获取错误?,java,event-handling,actionlistener,nested-class,Java,Event Handling,Actionlistener,Nested Class,这是我第一次尝试使用动作侦听器和事件处理。我正在尝试创建一个简单的GUI,它有3个按钮:home、about和tag。对于每个JButton,我都添加了一个侦听器对象,并为侦听器对象创建了一个嵌套类 public class interfacetest { public static void main(String[] args) { JFrame window = new JFrame("GUI Test"); window.setSize(250
home
、about
和tag
。对于每个JButton
,我都添加了一个侦听器对象,并为侦听器对象创建了一个嵌套类
public class interfacetest {
public static void main(String[] args) {
JFrame window = new JFrame("GUI Test");
window.setSize(250, 100);
window.setLocation(100, 100);
final JButton home = new JButton("Home");
final JButton about = new JButton("About");
final JButton tag = new JButton("Tag");
JMenuBar menu = new JMenuBar();
menu.add(home);
menu.add(about);
menu.add(tag);
menu.setVisible(true);
window.setJMenuBar(menu);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thehandler handler = new thehandler();
home.addActionListener(handler);
about.addActionListener(handler);
tag.addActionListener(handler);
window.setVisible(true);
}
// Here is my nested class.
private class thehandler implements ActionListener {
public void actionPerformed(ActionEvent event) {
String string = "";
if (event.getSource()==home)
string = string.format("home: %s, event.getActionCommand()");
else if (event.getSource()==about)
string = string.format("about: %s, event.getActionCommand()");
else if (event.getSource()==tag) string = string.format("tag: %s, event.getActionCommand()");
JOptionPane.showMessageDialog(null, string);
}
}
}
我在创建一个新的
处理程序对象时出错,该对象说:
“无法访问interfacetest类型的封闭实例。必须使用interfacetest类型的封闭实例(例如x.new a(),其中x是interfacetest的实例)来限定分配。”您有两种简单的方法来解决此问题:
私有静态类处理程序
(new interfacetest())。new thehandler()
(您可能需要重新构造代码,并且可能需要保留对interfacetest
实例的引用interfacetest iner = new interfacetest();
// Do things...
thehandler handler = iner.new thehandler(); // (e.g. x.new A() where x is an instance of interfacetest.)
说明:您的嵌套类是非静态的,但您试图像访问它一样访问它
- 如果类的成员不是静态的,则必须通过类的实例访问它:
(上面的选项2)classInstance.nonStaticMember
- 如果类的成员是静态的,您可以通过任何一种方式访问它,但正确的方式是通过类类型:
(上面的选项1)ClassType.staticMember
ClassType.nonStaticMember
,或this.nonStaticMember
(“无法访问interfacetest类型的封闭实例”)
您还可能会发现(从中)此术语非常有用:
嵌套类分为两类:静态类和非静态类。声明为静态的嵌套类称为静态嵌套类。非静态嵌套类称为内部类
注意事项:
- 在
上调用JFrame
,而不是手动pack()
setSize(…)
- 只有在对布局进行所有更改后,才能调用
setVisible(true)
- 当您的按钮执行不同的操作时,为每个按钮创建一个动作侦听器(这更有意义)
- 如果您的按钮执行类似的操作,例如仅使用不同的颜色创建同一面板,请创建一个单一的操作侦听器,其中构造函数采用该颜色(为其创建一个字段),并将其应用于
actionPerformed
- 在Java的命名约定中,类名以大写开头
外部
类的实例来实例化其内部
类。请查看。可能的