[英]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.