簡體   English   中英

如何在ActionListener中實現類?

[英]How do I implement a Class into an ActionListener?

如標題所示,我希望將Java項目中的現有類實現為ActionListener類。 為了幫助您理解我的問題,我將首先說明這種情況:

我被分配創建一個圖形包; 當滿足條件動作並完成該動作時,它將從CommandPanel JTextField獲取用戶輸入以從用戶繪制指定的行。 GUI由4個類組成,其中3個extend JPanels

CommandPanel的問題是嘗試將指定的GraphicsPanel類實現到CommandPanel ActionListener

我希望能夠在滿足要求時畫一條線,以確保在主類中查看時在同一GraphicsPanel中畫線(此處未包括)。

語句gppublic 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM