swing - Learning Event handling in Java -



swing - Learning Event handling in Java -

i learning event handling using java swing class. have trying different combinations based on tutorial new boston homepage. hav made class defining panels, jbuttons, jtextfields, , jlabels. have made class called "handler" contains actionperfomed-method, , have connected 2 textfields (item1 , item2) addactionlistener method. when run programme program want 2 textfields (this prompts joptionpane.showmessagedialog box display text want.

the problem comes when want joptionpane.showmessagedialog-window display text when force 1 of buttons: -instead of displaying next text "you pushed button number 1!" hoped code do, instead there appears empty joptionpane.showmessagedialog-window.

i reccon experienced java programmer see whats wrong in code easily.

here part of code must wrong:

private class thehandler implements actionlistener { public void actionperformed(actionevent event) { string text =""; if(event.getsource() == item1) text = string.format("you wrote %s in field 1!", event.getactioncommand()); else if (event.getsource() == item2) text = string.format("you wrote %s in field 2!", event.getactioncommand()); else if (event.getsource() == button1) text = "you pushed button number 1!"; else if (event.getsource() == button2) text = "you pushed button number 2!"; joptionpane.showmessagedialog(null, text);

add system.out.println() before joptionpane call:

system.out.println("text=" + text); joptionpane.showmessagedialog(null, text);

i bet find text empty string. why? maybe object references null.

another approach, may solve issue , doesn't rely on object references, utilize action commands:

button1.setactioncommand("doaction1"); public void actionperformed(actionevent event) { string actioncommand = event.getactioncommand(); if (actioncommand.equals("doaction1")) { // button 1 pressed } }

java swing event-handling action actionlistener

Comments

Popular posts from this blog

Delphi change the assembly code of a running process -

java - Parsing XML, skip certain tags -

c# - ASP.NET MVC Sequence contains no matching element -