正如标题所示,我希望将 Java 项目中的现有类实现为 ActionListener
类。为了帮助您理解我的问题,我将首先解释一下场景:
我被指派创建一个图形包;当条件操作满足并完成时,这将从 CommandPanel JTextField
获取用户输入,以绘制用户指定的线条。 GUI 由 4 个类组成,其中 3 个扩展 JPanels
。
我遇到的问题是尝试将指定的 GraphicsPanel
类实现到我的 CommandPanel
ActionListener
中。
我希望能够在满足要求时绘制一条线,以确保在与我的主类(此处不包括)中查看的同一 GraphicsPanel 中绘制该线。
语句gp
按照public CommandPanel(GraphicsPanel gp)
段中的预期工作,但是当我尝试将gp
调用到我的中时>ActionListener
在该面板中画一条线,它无法将其识别为预先存在的类。
可以进行进一步说明,以确保您理解当前的问题;任何帮助将不胜感激。 :-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;
}
}
关于java - 如何将类实现到 ActionListener 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42834967/