Java Event Listeners -
i'm trying separate components of java desktop app different classes. example, have menubar class, called mainclass, creates jmenubar.
normally, implement actionlistener in menubar class , override actionperformed() keep organized. if that, how can let mainclass know clicked?
i tried implementing own actionlistener, couldn't come solution capable of dispatching events other classes.
mainclass.java
public class mainclass extends jframe { private static void createandshowgui() { jframe.setdefaultlookandfeeldecorated(false); jframe frame = new jframe("main window"); frame.setdefaultcloseoperation(jframe.exit_on_close); menubar menubar = new menubar(); jmenubar mb = menubar.createmenu(); frame.setjmenubar(mb); frame.setsize(400,400); frame.setvisible(true); } public static void main(string[] args) { swingutilities.invokelater(new runnable() { public void run() { createandshowgui(); } }); } }
menubar.java
public class menubar implements actionlistener { public jmenubar createmenu() { jmenu menu; jmenuitem item; jmenubar menubar = new jmenubar(); menu = new jmenu("main"); menubar.add(menu); item = new jmenuitem("new"); menu.add(item); return menubar; } @override public void actionperformed(actionevent e) { jmenuitem source = (jmenuitem)(e.getsource()); system.out.println("action triggered on: "+source.gettext()); // *** let mainclass know clicked ?? } }
edit
i realized can create actionlistener in mainclass , pass menubar class, this:
amended mainclass.java
actionlistener l = new actionlistener() { public void actionperformed(actionevent ae) { system.out.println(ae.getactioncommand()); } }; menubar menubar = new menubar(); frame.setjmenubar(menubar.createmenu(l));
and then, in menubar, apply actionlistener each of menu items.
amended menubar.java
public jmenubar createmenu(actionlistener l) { item = new jmenuitem("hide when minimized"); item.addactionlistener(l); menu.add(item); }
one possible solution mainclass implements actionlistener
, pass instance menubar.createmenu():
public class menubar { public jmenubar createmenu( actionlistener l ) { ... menuitem.addactionlistener( l ); } ... }
mainclass side:
public class mainclass extends jframe { @override public void actionperformed(actionevent e) { object source = e.getsource(); system.out.println( "action triggered by: " + source ); } private static void createandshowgui() { ... frame.setdefaultcloseoperation(jframe.exit_on_close); menubar menubar = new menubar(); jmenubar mb = menubar.createmenu( frame ); frame.setjmenubar( mb ); ... } }
another way use java.beans.propertychangelistener , java.beans.propertychangesupport
Comments
Post a Comment