簡體   English   中英

即使在同一類中聲明了對象也無法找到對象

[英]Unable to find object even though it is declared in same class

我目前正在學習如何在Java中構建GUI,並且遇到以下錯誤“找不到符號-類監聽器”。

以下代碼創建單選按鈕,然后將它們與JLabel和操作偵聽器配對。 但是,即使我將監聽器作為button的參數提供,編譯器仍在告訴我找不到監聽器類。 有人知道為什么是這樣嗎?

在按鈕方法的參數行上發生錯誤。 非常感謝您的協助。

private void build(Stadium stadium)
    {  

       Listener listener = new Listener();

       add(button("Front", listener));
       add(button("Middle", listener));
       add(button("Back", listener));

    }

    private JRadioButton button(String label, Listener listener)
    {   JRadioButton button = new JRadioButton(label);
        button.addActionListener(listener);
        group.add(button);
        return button;  }

使用ActionListener而不是Listener ,它們與GUI中的Listener

private void build(Stadium stadium)
{  

   ActionListener listener = new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            // TODO Auto-generated method stub
            //Here you implement what you want your listener to execute on  button click;
        }
    };

   add(button("Front", listener));
   add(button("Middle", listener));
   add(button("Back", listener));

}

private JRadioButton button(String label, Listener listener)
{   JRadioButton button = new JRadioButton(label);
    button.addActionListener(listener);
    group.add(button);
    return button;  }

您需要一個ActionListener,而不是Listener。 您的類應該實現ActionListener( public class GUI implements ActionListener {

然后實現actionPerformed方法。

將此類的實例添加為偵聽器。

您可能需要導入Listener

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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