我正在尝试创建一个自定义事件,它侦听并响应按钮的点击。该按钮表示为一个椭圆形,用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){
}
这次活动是想从按钮的点击触发,在我如何写的代码这种特定的形式。 对我收到的错误的任何建议,如我的测试类中所述,或任何其他将不胜感激。非常感谢。
请大家学习java命名约定并坚持到他们 – kleopatra 2012-01-07 11:38:56