2017-03-16 52 views
0

正如标题所示,我希望将我的Java项目中的现有类实现为ActionListener类。为了帮助你理解我的问题,我将首先解释场景:如何在ActionListener中实现一个类?

我已被分配创建一个Graphics包;当满足并完成条件操作时,这将从用户输入CommandPanelJTextField以从用户绘制指定的行。该GUI由4个类组成,其中3个为extend JPanels

我的问题是试图实现指定的GraphicsPanel类到我的CommandPanelActionListener

我希望能够在符合要求时绘制一条线,以确保该线与我的主类(此处未包括)在相同的GraphicsPanel中绘制。

声明gp作品意在public CommandPanel(GraphicsPanel gp)段然而,当我尝试调用gp到我ActionListener画一条线在面板上,它没有认识到它作为一个已经存在的类。

可以进一步澄清以确保您了解手头的问题;任何帮助将不胜感激。 :-D

+0

为您的'ButtonListener'类构造一个构造函数,该构造函数将'GraphicsPanel'作为构造函数的参数,并将该引用存储在类本身中以对其进行修改。 – Orin

+0

谢谢@Orin,我现在正在研究它,因为我仍然用不同的方法来掌握:--D。 – Kez

回答

1

你必须存储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; 
    } 
} 
+0

你好@xxtesaxx我已经试过了,虽然它确实认识到代码有效,'gp.drawLine(Color.BLACK,0,100,Integer.parseInt(inputelements [1]),100);'仍然赢了'在这个班级里画线。它只会在'public CommandPanel'段中绘制该行。我会继续努力,直到我成功,谢谢。 :-D – Kez

+0

我不明白你的问题。所以你想在GraphicsPanel中画一些你传递CommandPanel作为构造函数的参数,对吧?或者你想绘制一个不同的GraphicsPanel? – xxtesaxx

+0

对不起,我想在actionPerformed代码段中画一条线,而这是有效的:\t'public class ButtonListener implements ActionListener { \t GraphicsPanel gp; \t public ButtonListener(GraphicsPanel gp){ \t this.gp = gp; \t gp.drawLine(Color.BLACK,0,100,100,100); \t}'这是在错误的部分,我理想希望它会在这里: – Kez

相关问题