[英]Java - Cannot find the symbol of an inner class that implements an ActionListener
我不再像在教科書中看到的那樣使按鈕成為動作偵聽器。 為此,我做了一個內部類。 當我嘗試調用內部類時,出現錯誤:找不到符號。
這是代碼:
package GUI;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ATMGUI extends GUI
{
public ATMGUI()
{
this.makePane();
this.makeButton("Withdraw");
button.addActionListener(new WithdrawListener());
pane.add(button);
this.makeText("Enter amount to withdraw: ");
pane.add(text);
this.makeTextField("Enter amount here");
pane.add(field);
this.makeFrame();
frame.add(pane);
class WithdrawListener implements ActionListener
{
public void actionPerformed(ActionEvent click)
{
System.out.println("This is a test.");
}
}
}
//------------------------------------------------------------------
public void makeFrame()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 500);
frame.setVisible(true);
}
public void makePane()
{
pane = new JPanel();
pane.setLayout(new GridLayout(3,3));
pane.setVisible(true);
}
public void makeButton(String buttonName)
{
button = new JButton(buttonName);
}
public void makeText(String addText)
{
text = new JLabel(addText);
}
public void makeTextField(String addText)
{
field = new JTextField(addText);
}
}
這是給我帶來麻煩的那一點
button.addActionListener(new WithdrawListener());
我在其他地方看到它必須以某種方式實例化。 我嘗試了類似的東西:
ATMGUI a = new ATMGUI();
ATMGUI.WithdrawListener w = a.new WithdrawListener();
然后輸入w作為參數,但這對我也不起作用。 不知道是否是因為我在子類中工作。 也不太確定是否需要以其他方式完成操作,因為我正在使用接口。
將WithdrawListener
放在構造函數上下文之外
public class ATMGUI extends GUI {
public ATMGUI() {
//...
button.addActionListener(new WithdrawListener());
//...
}
class WithdrawListener implements ActionListener {
public void actionPerformed(ActionEvent click) {
System.out.println("This is a test.");
}
}
在本地類聲明之后,將監聽器添加到按鈕。
public void abc(){
PQR pqr = new PQR(); // incorrect
class PQR {
}
}
正確的方法是
public void abc(){
class PQR {
}
PQR pqr = new PQR(); //correct
}
似乎您必須在使用前聲明本地類。 我測試的以下代碼段:
這個沒有顯示任何錯誤:
public void testFunc() {
class Test {
}
Test test = new Test();
}
但這確實做到了:
public void testFunc() {
Test test = new Test();
class Test {
}
}
編輯:很抱歉幾乎同時發布,下一次我將檢查三次是否有人發布。
不重復使用類時,建議使用匿名類型。
看看( 經常與聽眾一起使用 )-這是一個很好的答案! 從上面的鏈接引用
使用此方法可以使編碼更快一些,因為我不需要制作一個額外的類來實現ActionListener-我可以實例化一個匿名內部類而無需實際創建單獨的類。
我僅將這種技術用於“快速而骯臟的”任務,在這些任務中使整個課程變得不必要。 具有多個功能完全相同的匿名內部類應重構為實際類,無論是內部類還是單獨的類。
this.makePane();
this.makeButton("Withdraw");
button.addActionListener(new ActionListener() { //starts here
public void actionPerformed(ActionEvent click)
{
System.out.println("This is a test.");
}
});//ends
pane.add(button);
this.makeText("Enter amount to withdraw: ");
pane.add(text);
this.makeTextField("Enter amount here");
pane.add(field);
this.makeFrame();
frame.add(pane);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.