Calling an ActionEvent

杀马特。学长 韩版系。学妹 提交于 2019-12-13 07:51:17

问题


I am in the process of learning and creating a custom JButton/Component. I have the most of what I need, except I do not know how to call actionPerformed on my ActionListners.

Code:

package myProjects;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.*;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;

public class LukeButton extends JComponent{
    public static void main(String[] args){
        JFrame frame = new JFrame();
        frame.setTitle("Luke");
        frame.setSize(300, 300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        LukeButton lb = new LukeButton();
        lb.addActionListener(e->{
            System.out.println("Success");
        });
        frame.add(lb);

        frame.setVisible(true);
    }

private final ArrayList<ActionListener> listeners = new ArrayList<ActionListener>();

public LukeButton(){

}
public void addActionListener(ActionListener e){
    listeners.add(e);
}
public void paintComponent(Graphics g){

    super.paintComponent(g);

    Graphics2D g2 = (Graphics2D)g;
    Shape rec = new Rectangle2D.Float(10, 10, 60, 80);

    g2.setColor(Color.BLACK);
    g2.setStroke(new BasicStroke(5));
    g2.draw(rec);
    g2.setColor(Color.BLUE);
    g2.fill(rec);
}
}

Does anyone one know how to call the "listeners" ArrayList once the button is clicked? Thanks for taking your time.


回答1:


You need to loop over your list of ActionListeners and call their actionPerformed method, something like...

protected void fireActionPerformed() {
    if (!listeners.isEmpty()) {

        ActionEvent evt = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "LukeButton");
        for (ActionListener listener : listeners) {
            listener.actionPerformed(evt);
        }

    }
}

Now, you need to define the actions which might trigger a ActionEvent to occur, mouse click, key press etc and the call the fireActionPerformed method when they occur

Have a look at How to Write a Mouse Listener and How to Use Key Bindings for more details



来源:https://stackoverflow.com/questions/32002025/calling-an-actionevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!