在java中使用ActionListeners
我有两个类:一个用于绘制小程序,另一个用于添加actionListeners。小程序似乎没有正确添加actionListeners,因为我的小程序中没有任何函数可以工作。以下是我的代码片段: 这属于小程序类(StackApplet): actListen是Listener类的新实例化在java中使用ActionListeners,java,applet,Java,Applet,我有两个类:一个用于绘制小程序,另一个用于添加actionListeners。小程序似乎没有正确添加actionListeners,因为我的小程序中没有任何函数可以工作。以下是我的代码片段: 这属于小程序类(StackApplet): actListen是Listener类的新实例化 public void init() { try { SwingUtilities.invokeAndWait( new Runnable() {
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);
}
小程序似乎没有正确调用ActionListeners,我建议您传递引用并调用这些引用的公共方法,例如:
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);
}
除非在某些情况下,否则您应该尽量避免使用静态变量。这看起来很可疑,好像您正在使用静态变量来引用Swing组件。如果是这样,我强烈建议你不要这样做。没错。您建议我如何修改它?出于好奇,这将允许actionlisteners对小程序可见,如果我错了,请纠正我。@franklin:这个想法是将正在使用的活动对象的引用传递给需要它们的对象。因此,如果操作正确,这将允许将ActionListeners添加到需要它的组件中。然而,魔鬼总是在细节上。