![](/img/trans.png)
[英]How to use ActionListener when the button function is in another class
[英]How to use ActionListener in another class
我正在清理我的代码。 我读到我把ActionListener
另一个类是更好的。 这就是我做的。
但是在我的ActionListener
,除了在代码中的某个点,一切都有效,我得到了一个setSize(xx,xx)
。 我以前工作过,因为它在同一个班级。 但不是了。 我尝试了多种解决方案,但我无法理解。
ActionListener
:
public class ActionFrame implements ActionListener{
public void actionPerformed(ActionEvent e){
Object src = e.getSource();
if(src == Frame.Console_Bouton){
System.out.println("Bouton console");
if(getSize().getWidth() >= 750){
/** If True (Retirer) */
for(int i = 1090; i > 689; i--){
setSize(i, 490);
System.out.println("Rétractation du Frame");
}
}else{
/** If False (Etirer) */
for(int i = 689; i < 1090; i++){
setSize(i, 490);
System.out.println("Etirage du Frame");
}
}
}
...
至于错误,没有,它只会冻结程序。
猜测:可能这是一个提取ActionListener
不是一个好主意的情况,因为它使用对象的private
方法。
具有通用/可重用功能的类应该是独立的。 只要它们是用于特定用途,实践(根本不是!)只是将它们尽可能地靠近它们使用的地方。 我可以想象你的setSize
方法不是你的类的公共接口的一部分,所以ActionListener
只是“粘合”将事件耦合到你的特定类。
在这种情况下,您将创建一个“微小”胶水线:
abstract class ActionAdapter implements ActionListener {
}
...
frame.Console_Bouton.addActionListener(
new ActionAdapter(){ // anonymous inner class
void actionPerformed(ActionEvent e){
... // (no need to check source!)
}
});
创建一个新类:
ButtonAction implements actionListner
{
//put the code above here
}
这样做的好方法是使用Callback机制 。
我在这里发布了相同背景的答案
- 编辑 -
从ActionEvent
获取源代码然后找到它的父级(如果需要,获取父级的父级,直到获得需要重新调整大小的所需组件)并在其上调用setSize()
。
在控制器中创建View的实例
将setSize(xx,yy)
方法的访问修饰符从private
更改为public
。
将actionPerformed()
setSize
替换为view.setSize(xx,yy)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.