Я пытаюсь создать пользовательское событие, которое слушает и реагирует на нажатия кнопки.Кнопка представлена в виде овала, нарисованного в методе paintComponent на изображении в JFrame.При щелчке по нему предполагается изменить цвет, а затем при повторном нажатии вернуться к предыдущему цвету - как кнопка ВКЛ / ВЫКЛ.
Я создал для него интерфейс:
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;
}
}
Класс компонента для представления кнопки:
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){
}
Предполагается, что событие инициируется нажатием кнопки, в этом конкретном формате, как я написал код.Любой совет по поводу ошибки, которую я получил, как указано в моем тестовом классе, или что-нибудь еще, будет высоко ценится.Большое спасибо.