我有两个类:一个绘制applet,另一个添加actionListeners。似乎applet没有正确添加actionListeners,因为我的applet中没有任何函数可以工作。以下是我的代码片段:
这属于applet类(StackApplet):
actListen是Listener类的新实例。
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
@Override
public void run() {
actListen.invokePush();
actListen.invokePop();
}
});
} catch (Exception e) {
}
这属于侦听器类:
public void invokePush() {
pushListener = new ActionListener() {
public void actionPerformed(ActionEvent act) {
int currentSize = (int)myStack.size();
try {
if (currentSize == ceiling) {
StackApplet.pushField.setEnabled(false);
StackApplet.pushField.setForeground(Color.RED);
StackApplet.pushField.setText("Error: The stack is already full");
} else if (currentSize == ceiling - 1) {
StackApplet.pushField.setForeground(Color.YELLOW);
StackApplet.pushField.setText("Warning: The stack is almost full");
} else if (currentSize == 0) {
StackApplet.pushField.setText("weenie");
}
} catch (Exception e) {
}
}
};
StackApplet.pushBtn.addActionListener(pushListener);
}
似乎Applet没有正确调用ActionListeners
答案 0 :(得分:2)
我建议您传递引用并在这些引用上调用公共方法,例如:
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
@Override
public void run() {
ActListen actListenInstance = new ActListen(StackApplet.this);
actListenInstance.invokePush();
actListenInstance.invokePop();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
然后在ActListen的构造函数中接受StackApplet引用,然后使用该实例调用StackApplet的非静态方法。
类似的东西,
public void invokePush() {
pushListener = new ActionListener() {
public void actionPerformed(ActionEvent act) {
int currentSize = (int)myStack.size();
try {
if (currentSize == ceiling) {
stackAppletInstance.ceilingReached();
} else if (currentSize == ceiling - 1) {
stackAppletInstance.ceilingAlmostReached();
} else if (currentSize == 0) {
stackAppletInstance.stackEmpty();
}
} catch (Exception e) {
e.printStackTrace(); // ***** never leave this blank!
}
}
};
stackAppletInstance.addPushListener(pushListener);
}
除非在某些情况下,否则您将努力避免使用静态内容。