在 Java 中为 CustomButton 创建 ActionEvent 对象

发布于 2024-09-02 19:14:08 字数 4143 浏览 4 评论 0原文

对于硬件分配,我们应该创建一个自定义按钮来熟悉 Swing 和响应事件。我们还打算让这个按钮成为一个事件源,这让我很困惑。我有一个 ArrayList 来跟踪将注册以侦听我的 CustomButton 的侦听器。我感到困惑的是如何通知听众。我的老师暗示我尝试做一个通知和重写 actionPerformed ,但后来我不确定如何创建一个 ActionEvent 对象查看构造函数文档。来源、id、字符串都让我困惑。任何帮助将不胜感激。

代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;

public class CustomButton 
{
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                CustomButtonFrame frame = new CustomButtonFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }

    public void addActionListener(ActionListener al)
    {
        listenerList.add(al);
    }

    public void removeActionListener(ActionListener al)
    {
        listenerList.remove(al);
    }

    public void actionPerformed(ActionEvent e) 
    {
        System.out.println("Button Clicked!");
    }

    private void notifyListeners()
    {
        ActionEvent event = new ActionEvent(CONFUSED HERE!!!!;
        for (ActionListener action : listenerList) {
            action.actionPerfomed(event);
        }
    }

    List<ActionListener> listenerList = new ArrayList<ActionListener>();
}

class CustomButtonFrame extends JFrame
{
    // constructor for CustomButtonFrame
    public CustomButtonFrame()
    {
        setTitle("Custom Button");
        CustomButtonSetup buttonSetup = new CustomButtonSetup();
        this.add(buttonSetup);
        this.pack();
    }
}

class CustomButtonSetup extends JComponent 
{
    public CustomButtonSetup()
    {
        ButtonAction buttonClicked = new ButtonAction();
        this.addMouseListener(buttonClicked);
    }

    // because frame includes borders and insets, use this method
    public Dimension getPreferredSize()
    {
        return new Dimension(200, 200);
    }

    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;

        // first triangle coords
        int x[] = new int[TRIANGLE_SIDES];
        int y[] = new int[TRIANGLE_SIDES];
        x[0] = 0;   y[0] = 0;
        x[1] = 200; y[1] = 0;
        x[2] = 0;   y[2] = 200;
        Polygon firstTriangle = new Polygon(x, y, TRIANGLE_SIDES);

        // second triangle coords
        x[0] = 0;   y[0] = 200;     
        x[1] = 200; y[1] = 200;
        x[2] = 200; y[2] = 0;
        Polygon secondTriangle = new Polygon(x, y, TRIANGLE_SIDES);

        g2.drawPolygon(firstTriangle);
        g2.setColor(firstColor);
        g2.fillPolygon(firstTriangle);

        g2.drawPolygon(secondTriangle);
        g2.setColor(secondColor);
        g2.fillPolygon(secondTriangle);

        // draw rectangle 10 pixels off border
        int s1[] = new int[RECT_SIDES];
        int s2[] = new int[RECT_SIDES];
        s1[0] = 5;    s2[0] = 5;
        s1[1] = 195;  s2[1] = 5;
        s1[2] = 195;  s2[2] = 195;
        s1[3] = 5;    s2[3] = 195;
        Polygon rectangle = new Polygon(s1, s2, RECT_SIDES);
        g2.drawPolygon(rectangle);
        g2.setColor(thirdColor);
        g2.fillPolygon(rectangle);  
    }

    private class ButtonAction implements MouseListener {
        public void mousePressed(MouseEvent e)
        {
            System.out.println("Click!");
            firstColor = Color.GRAY;
            secondColor = Color.WHITE;

            repaint();
        }

        public void mouseReleased(MouseEvent e)
        {
            System.out.println("Released!");
            firstColor = Color.WHITE;
            secondColor = Color.GRAY;
            repaint();
        }

        public void mouseEntered(MouseEvent e)
        {}

        public void mouseExited(MouseEvent e)
        {}

        public void mouseClicked(MouseEvent e)
        {}
    }

    public static final int TRIANGLE_SIDES = 3;
    public static final int RECT_SIDES = 4;
    private Color firstColor = Color.WHITE;
    private Color secondColor = Color.DARK_GRAY;
    private Color thirdColor = Color.LIGHT_GRAY;
}

For a hw assignment, we were supposed to create a custom button to get familiar with swing and responding to events. We were also to make this button an event source which confuses me. I have an ArrayList to keep track of listeners that would register to listen to my CustomButton. What I am getting confused on is how to notify the listeners. My teacher hinted at having a notify and overriding actionPerformed which I tried doing, but then I wasn't sure how to create an ActionEvent object looking at the constructor documentation. The source, id, string all confuses me. Any help would be appreciated.

code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.List;
import java.util.ArrayList;

public class CustomButton 
{
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                CustomButtonFrame frame = new CustomButtonFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setVisible(true);
            }
        });
    }

    public void addActionListener(ActionListener al)
    {
        listenerList.add(al);
    }

    public void removeActionListener(ActionListener al)
    {
        listenerList.remove(al);
    }

    public void actionPerformed(ActionEvent e) 
    {
        System.out.println("Button Clicked!");
    }

    private void notifyListeners()
    {
        ActionEvent event = new ActionEvent(CONFUSED HERE!!!!;
        for (ActionListener action : listenerList) {
            action.actionPerfomed(event);
        }
    }

    List<ActionListener> listenerList = new ArrayList<ActionListener>();
}

class CustomButtonFrame extends JFrame
{
    // constructor for CustomButtonFrame
    public CustomButtonFrame()
    {
        setTitle("Custom Button");
        CustomButtonSetup buttonSetup = new CustomButtonSetup();
        this.add(buttonSetup);
        this.pack();
    }
}

class CustomButtonSetup extends JComponent 
{
    public CustomButtonSetup()
    {
        ButtonAction buttonClicked = new ButtonAction();
        this.addMouseListener(buttonClicked);
    }

    // because frame includes borders and insets, use this method
    public Dimension getPreferredSize()
    {
        return new Dimension(200, 200);
    }

    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;

        // first triangle coords
        int x[] = new int[TRIANGLE_SIDES];
        int y[] = new int[TRIANGLE_SIDES];
        x[0] = 0;   y[0] = 0;
        x[1] = 200; y[1] = 0;
        x[2] = 0;   y[2] = 200;
        Polygon firstTriangle = new Polygon(x, y, TRIANGLE_SIDES);

        // second triangle coords
        x[0] = 0;   y[0] = 200;     
        x[1] = 200; y[1] = 200;
        x[2] = 200; y[2] = 0;
        Polygon secondTriangle = new Polygon(x, y, TRIANGLE_SIDES);

        g2.drawPolygon(firstTriangle);
        g2.setColor(firstColor);
        g2.fillPolygon(firstTriangle);

        g2.drawPolygon(secondTriangle);
        g2.setColor(secondColor);
        g2.fillPolygon(secondTriangle);

        // draw rectangle 10 pixels off border
        int s1[] = new int[RECT_SIDES];
        int s2[] = new int[RECT_SIDES];
        s1[0] = 5;    s2[0] = 5;
        s1[1] = 195;  s2[1] = 5;
        s1[2] = 195;  s2[2] = 195;
        s1[3] = 5;    s2[3] = 195;
        Polygon rectangle = new Polygon(s1, s2, RECT_SIDES);
        g2.drawPolygon(rectangle);
        g2.setColor(thirdColor);
        g2.fillPolygon(rectangle);  
    }

    private class ButtonAction implements MouseListener {
        public void mousePressed(MouseEvent e)
        {
            System.out.println("Click!");
            firstColor = Color.GRAY;
            secondColor = Color.WHITE;

            repaint();
        }

        public void mouseReleased(MouseEvent e)
        {
            System.out.println("Released!");
            firstColor = Color.WHITE;
            secondColor = Color.GRAY;
            repaint();
        }

        public void mouseEntered(MouseEvent e)
        {}

        public void mouseExited(MouseEvent e)
        {}

        public void mouseClicked(MouseEvent e)
        {}
    }

    public static final int TRIANGLE_SIDES = 3;
    public static final int RECT_SIDES = 4;
    private Color firstColor = Color.WHITE;
    private Color secondColor = Color.DARK_GRAY;
    private Color thirdColor = Color.LIGHT_GRAY;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

何以笙箫默 2024-09-09 19:14:08

阅读有关 ActionEvent 的文档。有一节是关于它的构造函数的,请阅读每个参数的含义。

对于您的情况,适用的代码将如下所示:

int uniqueId = System.currentTimeMillis().intValue();
String commandName = ""; //it can be like "show" or "hide" or whatever else; 
                         //you can get this string with getActionCommand() method
                         //and make some actions based on its value
                         //... but you don't need it now
ActionEvent event = new ActionEvent(this, uniqueId, commandName);

Read documentation on ActionEvent. There is a section about its constructors, read what each parameter means.

For your case appliable code will be like this:

int uniqueId = System.currentTimeMillis().intValue();
String commandName = ""; //it can be like "show" or "hide" or whatever else; 
                         //you can get this string with getActionCommand() method
                         //and make some actions based on its value
                         //... but you don't need it now
ActionEvent event = new ActionEvent(this, uniqueId, commandName);
终遇你 2024-09-09 19:14:08

总体思路是:

  • 您维护一组侦听器。
  • 如果您必须通知侦听器(发生了事件),则可以迭代侦听器集合并在每个侦听器(在您的情况下为 ActionListener)上调用适当的方法。

我没有看到 ActionListener 和 ActionEvent 的声明。根据您的模式,ActionEvent 很可能会有一种表示实际事件的状态字段,因此它有一个类似 public ActionEvent(int value) 等的构造函数。侦听器接收 ActionEvent,查看 ActionEvent 对象内部,然后了解为什么他收到通知。

编辑

从其他人的回答中我刚刚了解到 ActionListener 和 ActionEvent 是 AWT 类。所以看看他们的java文档,我的其余答案应该仍然有效。

编辑2

最简单的构造函数是这个:

public ActionEvent(Object source, int id, String command);

是触发事件的对象,因此在您的情况下,最有可能是按钮。 id 标识事件的类型。从 ActionEventAWTEvent 的静态字段中进行选择。该命令是您可以放置​​有关事件的附加信息的区域。

The general idea is:

  • You maintain a collection of listeners.
  • If you have to notify the listeners (an event occured), you iterate through the collection of listeners and call the appropriate method on each Listener (ActionListener in your case).

I don't see the declarations of ActionListener and ActionEvent. With your pattern, the ActionEvent most likely will have a sort of status field which represents the actual event, so it has a constructor like public ActionEvent(int value) or so. The listener receives the ActionEvent, looks inside the ActionEvent object and nows, why he has been notified.

EDIT

From other peoples answer I just learned that ActionListener and ActionEvent are AWT classes. So look at their java docs, the rest of my answer should still be valid.

EDIT 2

The easiest constructor is this one:

public ActionEvent(Object source, int id, String command);

The sourceis the object, that fired the event, so in your case, most likely the button. The id identifies the type of event. Choose on from the static fields at ActionEvent or AWTEvent. The command is an area where you can put additional information regarding the event.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文