簡體   English   中英

擴展ActionEvent嗎? 沒有自定義偵聽器的自定義事件?

[英]Extending ActionEvent? A custom event, without a custom listener?

目前,我有2個對象涉及到:一個控制器和一個創建事件的類。

我已經在源類中使用ActionListener變量進行了所有工作,該變量由控制器的匿名ActionListener對象和方法設置。

但是我需要從控制器中的源類訪問數據。 我能夠擴展EventListener並使用自定義EventObject,但這似乎對於一點點數據來說有點過大。

有沒有簡單的方法來擴展ActionEvent並創建一個我可以在偵聽器的actionPerformed()方法中訪問的額外變量? ActionEvent的構造函數讓我感到困惑。

public class NotesEvent extends ActionEvent{
    public NotesEvent(Object source, int id, String command){
        super(source, id, command);
    }
}

我不知道實例化事件時傳遞給“標識符”的內容。

也許我錯過了一些簡單的事情-我只是真正學會了使用自定義類進行長期的操作。

任何幫助,將不勝感激

我犯了一個錯誤,就是沒有在控制器中向下轉換自定義事件,所以我認為ActionListener不能與自定義事件一起很好地使用-但這確實(我最初的想法)

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;

public class Target {
    ActionListener listener;
    int data = 1;

    public Target(){
        JButton b = new JButton("Press Me");

        b.addActionListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e){
                CustomEvent ce = new CustomEvent(data, Target.this, 0, "Command");
                if(listener != null) listener.actionPerformed(ce);
            }
        });
    }

    public void setListener(ActionListener listener){
        listener = listener;
    }  
}

class CustomEvent extends ActionEvent{
    int data;
    CustomEvent(int data, Object source, int id, String command){
        super(source, id, command);
        this.data = data;
    }

    public int getData(){
        return data;
    }
}

控制器類:

import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener;
import javax.swing.JButton;

public class Controller {
    Target t = new Target();

    public static void main(String[] args){
        Controller c = new Controller();
    }

    public Controller(){
        t.setListener(new ActionListener(){
            @Override
            public void actionPerformed(ActionEvent e) {
               //here was my problem 
               System.out.println(((CustomEvent)e).getID());
            }
        });
    }
}

我仍然不確定我應該傳遞給ActionEvent構造函數的數據。

希望以上內容可以清楚說明我要實現的目標(我知道就UI而言,它實際上還沒有完成。)

暫無
暫無

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

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