2017-03-16 51 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

相關問題