简体   繁体   English

Java GUI - MouseListener和ActionListener可以在同一个类中吗?

[英]Java GUI - MouseListener and ActionListener are possible to in same class?

CircleListener is an inner class in my panel class and it involves MouseListener interface now. CircleListener是我的面板类中的内部类,它现在涉及MouseListener接口。 MouseRelased method checks if the clicked area is encircled by a circle and if so it sets that shape to selected and removes the selected ones. MouseRelased方法检查单击的区域是否被圆圈包围,如果是,则将该形状设置为选中并删除选定的形状。

Now I need to an ActionListener to add random sized circles to this panel with a "timer" object. 现在我需要一个ActionListener来向这个面板添加一个带有“timer”对象的随机大小的圆圈。 Question: Is it possible to implement "ActionListener" to CircleListener or it is better to create another inner class for "ActionListener"? 问题:是否可以将“ActionListener”实现到CircleListener,或者最好为“ActionListener”创建另一个内部类?

Thanks in advance 提前致谢

private class CircleListener implements MouseListener
{
    ShapesCanvas canvas;
    ShapeContainer container;
    Shape possibleShape;

    private CircleListener(ShapesCanvas canv, ShapeContainer cont)
    {
        this.canvas = canv;
        this.container = cont;
    }

    public void MouseRelased (MouseEvent e)
    {
        possibleShape = container.contains( e.getX(), e.getY());

        if( possibleShape != null)
        {
            ( (Selectable)possibleShape).setSelected(true);
            container.removeSelected();
        }
        canvas.repaint(); //repaints the last situation
    }

It is definetly possible, just declare 这是绝对可能的,只是声明

private class CircleListener implements MouseListener, ActionListener

You can create two classes instead, and that is actually what I prefer, because then you have two distinct entities with clearly defined purposes. 你可以创建两个类,这实际上是我喜欢的,因为那时你有两个明确定义的不同实体。 Each entity is responsible for just one function. 每个实体只负责一个功能。

But both approaches are valid. 但这两种方法都是有效的。

Syntactically you can define a class that implements both interfaces. 从语法上讲,您可以定义一个实现两个接口的类。 Define two classes if they server completely different purposes, put the codes in one if they share some information such as the radius of circles. 如果它们服务于完全不同的目的,则定义两个类,如果它们共享一些信息(例如圆的半径),则将代码放在一个中。

what i don't understand here is that ActionListener is what responds to a GUI event rather than a Timer event 我不明白的是ActionListener响应GUI事件而不是Timer事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM