java - Get buttons in frame -


i need add listener each button this:

 for(i = 0; < 10; i++)      buttons[i].addactionlistener(actionlistener); 

the buttons exist, , need list of buttons in frame.

you use getcomponents() method jbuttons in frame.

a working example:

frame = new jframe(); frame.setvisible(true); frame.setsize(250, 250); frame.setdefaultcloseoperation(windowconstants.exit_on_close);  gridlayout layout = new gridlayout(); frame.setlayout(layout);  (int = 0; < 10; ++i)     frame.getcontentpane().add(new jbutton("a"));  component[] components = frame.getcontentpane().getcomponents(); actionlistener actionlistener = new actionlistener() {     @override     public void actionperformed(actionevent e)     {         system.out.println("hello");     } };  (component component : components) {     if (component instanceof jbutton)     {         ((jbutton) component).addactionlistener(actionlistener);     } } 

it adds 10 buttons , add listener.

hint: don't in way if create buttons dinamically, overkill!

the above more simple:

frame = new jframe(); frame.setvisible(true); frame.setsize(250, 250); frame.setdefaultcloseoperation(windowconstants.exit_on_close);  gridlayout layout = new gridlayout(); frame.setlayout(layout);  actionlistener actionlistener = new actionlistener() {     @override     public void actionperformed(actionevent e)     {         system.out.println("hello");     } };  (int = 0; < 10; ++i) {     jbutton button = new jbutton("a");     button.addactionlistener(actionlistener);     frame.getcontentpane().add(button); } 

same code, without 2 fors!

but if don't know how buttons have first code ok, if know , want avoid action before happens, consider using boolean variable.

something like:

// out boolean specialevent;  // inside actionlistener actionlistener = new actionlistener() {     @override     public void actionperformed(actionevent e)     {         if (!specialevent) return; // special event still false no can't         system.out.println("hello");     } }; 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -