Thursday 15 March 2012

swing - Why isn't my anonymous class action listener not working to exit the Java GUI? -



swing - Why isn't my anonymous class action listener not working to exit the Java GUI? -

ob1 jbutton, , when clicked on dialog pop up. 1 time pops up, pop-up window "hello there" , "hi" button underneath. when "hi" clicked on, exit gui together. here seem i've done correctly, don't understand why it's not working. please help.

thank you

ob1.addactionlistener(new actionlistener(){ public void actionperformed(actionevent ae){ jdialog jd = new jdialog(); //pop-up window jd.setlocationrelativeto(null); jd.setsize(350, 150); jd.setmodal(true); jpanel jp = new jpanel(); jp.setlayout(new boxlayout(jp, boxlayout.y_axis)); jlabel jl = new jlabel("hello there"); jbutton jb3 = new jbutton("hi"); jp.add(jl); jp.add(jb3); jd.add(jp); jd.setvisible(true); //acition listener hi button , when clicked on supposed exit gui jb3.addactionlistener(new actionlistener(){ public void actionperformed(actionevent ae){ system.exit(0); } }); } });

because dialog modal...

jd.setmodal(true);

the code stop at...

jd.setvisible(true);

until dialog closed, meaning that...

//acition listener hi button , when clicked on supposed exit gui jb3.addactionlistener(new actionlistener(){ public void actionperformed(actionevent ae){ system.exit(0); } });

is not called until after dialog closed, meaning actionlistener not registered button until after dialog closed, kind of meaningless...

switch 2 lines...

jb3.addactionlistener(...); jd.setvisible(true);

take @ how create dialogs more details...

ps- don't need actionlistener, can phone call system.exit(0) after setvisible call, jbutton dispose of dialog.

pps- utilize joptionpane accomplish same result in less lines of code ;)

updated...

by it's nature, joptionpane.showxxx blocking method, until dialog shows closed, method not return.

this means can assume 1 method returns, dialog has been closed on user pressed "ok"...

joptionpane.showmessagedialog(jf, "hello there", "window", joptionpane.information_message); system.exit(0);

java swing actionlistener

No comments:

Post a Comment