调用一个ActionEvent [英] Calling an ActionEvent

查看:229
本文介绍了调用一个ActionEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习和创建自定义JButton / Component。除了我不知道如何在ActionListners上调用actionPerformed之外,我已拥有大部分需求。

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.

代码:

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);
}
}

有人知道如何称呼听众吗? ArrayList一旦单击按钮?感谢您抽出宝贵的时间。

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

推荐答案

您需要遍历 ActionListener s并调用其 actionPerformed 方法,类似...

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);
        }

    }
}

现在,您需要定义可能触发 ActionEvent 发生的动作,鼠标单击,按键等,并调用 fireActionPerformed 发生时的方法

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

这篇关于调用一个ActionEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆