【发布时间】:2014-05-25 01:28:57
【问题描述】:
这是我第一次尝试使用动作监听器和事件处理。我正在尝试创建一个具有 3 个按钮的简单 GUI: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);
}
}
}
我在创建一个新的thehandler 对象时收到错误消息: “没有可访问类型为 interfacetest 的封闭实例。必须使用封闭实例限定分配interfacetest 类型的(例如 x.new A() 其中 x 是 interfacetest 的一个实例)。"
【问题讨论】:
-
什么编译器/lint 会产生如此冗长的消息?从您的帖子中很难推断出您的班级结构。你的 main() 方法属于哪个类?
-
抱歉没有说清楚。但是我已经在代码中添加了这个类。 Main() 属于:interfacetest 类。我也使用eclipse。
-
那么你的信息很清楚:你需要一个
outer类的实例来实例化它的inner类。看看Inner/Outer class obj.new。
标签: java event-handling actionlistener nested-class