2012-01-06 38 views
0

我正在尝试创建一个自定义事件,它侦听并响应按钮的点击。该按钮表示为一个椭圆形,用JFrame中显示的paintComponent方法绘制。当它被点击时,它应该改变颜色,然后再次点击时返回到前一种颜色 - 就像一个ON/OFF按钮。Java - 使用按钮和鼠标点击创建自定义事件

我已经创建了一个接口,用于它:

public interface gListener { 
    public void gActionPerformed(GooEvent e); 
} 

一个事件监听器:

public class gEvent extends java.util.EventObject 
{ 
    private int x, y; 
    private int value; 
    private gComponent source; 
    final static int ON = 1; 
    final static int OFF = 0; 

public gEvent(int x, int y, int val, gComponent source) 
{ 
    super(source); 
    this.x = x; 
    this.y = y; 
    value = val; 
    this.source = source; 
} 
} 

A组分类来表示按钮:

public abstract class gComponent { 

    //Link an arraylist to the gListener interface. 
    ArrayList <gListener> listeners = new ArrayList<gListener>(); 
    int x, y, w, h; 

    public gComponent(int x, int y, int w, int h) { 
     this.x = x; this.y = y; this.w = w; this.h = h; 
    } 

//Add listener to arraylist 
    public void addListener(gListener gl) 
    { 
     listeners.add(gl); 
    } 

    // Dispatches the gEvent e to all registered listeners. 
    protected void send (gEvent e){ 
     e = new gEvent(x, y, w, this); 
     Iterator<GooListener> i = listeners.iterator(); 
     while (i.hasNext()) 
     { 
      ((gListener) i.next()).gActionPerformed(e); 
     } 
    } 
} 

的gComponent类被扩展在一个按钮类(gButton)中,这是paintComponent和mouseClicked方法的地方调用。最后...我有扩展JPanel并实现gListener接口的测试类。主要方法如下所示:

public static void main(String[] args) { 
     // JFrame code goes here.... 


     gButton button = new gButton(20,20,20,20); //Click oval shape 

      //Using addListener method from gComponent superclass. 
      //The 'this' code is throwing error: cannot use this in a static context. 
     button.addListener(this); 
} 

    //Cause something to happen - stop/start animation. 
    public void gooActionPerformed(GooEvent e){ 


    } 

这次活动是想从按钮的点击触发,在我如何写的代码这种特定的形式。 对我收到的错误的任何建议,如我的测试类中所述,或任何其他将不胜感激。非常感谢。

+0

请大家学习java命名约定并坚持到他们 – kleopatra 2012-01-07 11:38:56

回答

1

这简直......令人惊叹。

但无论如何,在main()这样的静态方法中没有this。如果要使用gooActionPerformed()方法创建对象,则需要创建main()出现的任何类的实例,并使用该实例代替this

+0

当然!谢谢你。任何想法如何处理发生的鼠标事件? – AWb 2012-01-06 12:47:20

+0

如果你需要实际处理鼠标点击,你应该摆脱所有这些,并使用内置的AWT事件机制。 – 2012-01-06 13:02:11

+0

我知道,但是我设计代码的格式是需要的。我仍然试图了解自定义事件;自定义事件如何检测到鼠标点击? java.util.EventObject能做到这一点吗? – AWb 2012-01-06 13:15:08