java - Separating components into classes -


i'm creating "gui" application, aim make code clear , separating "gui" components classes (you'll see below mean), goes menu bar, i'm wonder now, since want implement actionlistener them, best in class, example in case of menu bar class, in class or implement action listener in main , implement abstract method use methods want perform action?

import java.awt.event.actionevent; import java.awt.event.actionlistener; import javax.swing.jframe;  public final class main extends jframe {      private menubar menubar;      public main() {         settitle("gui");         setsize(300, 200);         setlocationrelativeto(null);         setvisible(true);         setdefaultcloseoperation(exit_on_close);          initgui();     }      public void initgui() {         menubar = new menubar(this);         // last update before started posting this, decided         // access exitmenu variable , addactionlistener here, not working         menubar.exitmenu.addactionlistener(new actionlistener() {              @override             public void actionperformed(actionevent e) {                 system.exit(0);             }         });     }      public static void main(string[] args) {         new main();     }  } 

menu bar class:

import javax.swing.jframe; import javax.swing.jmenu; import javax.swing.jmenubar;  public final class menubar {      public jmenu newmenu;     public jmenu aboutmemenu;     public jmenu exitmenu;      public menubar(jframe jframe) {         jmenubar menubar = new jmenubar();          initnew(menubar);         initaboutme(menubar);         initexit(menubar);          jframe.setjmenubar(menubar);     }      public void initnew(jmenubar menubar) {         newmenu = new jmenu("new");           menubar.add(newmenu);     }      public void initaboutme(jmenubar menubar) {         aboutmemenu = new jmenu("about me");           menubar.add(aboutmemenu);     }      public void initexit(jmenubar menubar) {         exitmenu = new jmenu("exit");         menubar.add(exitmenu);     }   } 

one standard approach have main class, or class "close" main, handle or of actions. there typically giant switch statement based upon action.getactioncommand() passes control appropriate function. 1 not approach, have advantage it's simple follow.

imo far superior approach create abstractactions , hook them. can organized in whatever way makes sense application. what's nice nicely encapsulated, feel more "oo-like", etc.... also, multiple gui elements can share action. e.g. both button , menu can invoke "savefileaction" action. , actions can centrally enabled , disabled. if there no file save, "savefileaction" can disabled.


Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

CSS3 Transition to highlight new elements created in JQuery -