I am trying to create a custom event which listens and responses to the clicks of a button. The button is represented as an oval, drawn in a paintComponent method on shown in a JFrame. When it is clicked, it is supposed to change colour, then return to a previous colour when clicked again – like an ON / OFF button.
I have created an interface for it:
public interface gListener {
public void gActionPerformed(GooEvent e);
}
An event listener:
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 component class to represent the button:
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);
}
}
}
The gComponent class is extended in a button class (gButton), which is where the paintComponent and mouseClicked methods are called. And lastly… I have the test class which extends a JPanel and implements the gListener interface. The main method looks like the following:
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){
}
The event is suppose to trigger from a click of the button, in this particular format of how I have written the code.
Any advice to the error I received as stated in my test class, or anything else would be much appreciated. Many thanks.
This is simply… breathtaking.
But in any case, there’s no
thisin a static method likemain(). If you want an object with agooActionPerformed()method, then you need to create an instance of whatever classmain()appears in, and use that instance in place ofthis.