我有两个类:一个用于绘制applet,另一个用于添加actionListeners。小程序似乎没有正确添加actionListeners,因为我的小程序中的所有函数都不起作用。以下是我的代码片段:
这属于小程序类(StackApplet):
actListen是Listener类的新实例化。
public void init() {
try {
SwingUtilities.invokeAndWait(
new Runnable() {
@Override
public void run() {
actListen.invokePush();
actListen.invokePop();
}
});
} catch (Exception e) {
}这属于listener类:
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);
}小程序似乎没有正确地调用ActionListeners
发布于 2012-10-22 01:43:27
我建议您传递引用并在这些引用上调用公共方法,如下所示:
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);
}您将希望努力避免使用静态任何东西,除非在某些情况下。
https://stackoverflow.com/questions/13000277
复制相似问题