![](/img/trans.png)
[英]How do I implement ActionListener with a non abstract class in Java
[英]How do I implement a Class into an ActionListener?
如标题所示,我希望将Java项目中的现有类实现为ActionListener
类。 为了帮助您理解我的问题,我将首先说明这种情况:
我被分配创建一个图形包; 当满足条件动作并完成该动作时,它将从CommandPanel JTextField
获取用户输入以从用户绘制指定的行。 GUI由4个类组成,其中3个extend JPanels
。
我CommandPanel
的问题是尝试将指定的GraphicsPanel
类实现到CommandPanel
ActionListener
。
我希望能够在满足要求时画一条线,以确保在主类中查看时在同一GraphicsPanel中画线(此处未包括)。
语句gp
在public CommandPanel(GraphicsPanel gp)
段中按预期工作,但是当我尝试在ActionListener
调用gp
在该面板中画一条线时,它无法将其识别为预先存在的类。
可以进行进一步的澄清,以确保您了解当前的问题; 任何帮助将不胜感激。 :-D
调用构造函数时,必须将gp作为实例变量存储在CommandPanel中:
private GraphicsPanel gp;
public CommandPanel(GraphicsPanel gp) {
this.gp = gp;
}
或者,将gp传递给ActionListener并将其存储在其中的实例变量中:
public CommandPanel(GraphicsPanel gp) {
ButtonListener listener = new ButtonListener(gp);
}
public class ButtonListener implements ActionListener {
GraphicsPanel gp;
public ButtonListener(GraphicsPanel gp){
this.gp = gp;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.