java - Why does my ActionListener only work for one of my buttons? -
this code:
import java.io.*; import javax.swing.*; import java.awt.event.* ; class plugin extends jframe implements actionlistener { jpanel pnl = new jpanel(); public static void main(string args[]) { plugin gui = new plugin(); } jtextfield progname = new jtextfield("program name"); jbutton pnameok = new jbutton("ok"); jtextfield endtxt = new jtextfield("type of file"); jbutton endok = new jbutton("ok"); jbutton stop = new jbutton("stop server"); public plugin() { super(); add(pnl); pnl.add(stop); pnl.add(progname); pnl.add(pnameok); pnl.add(endtxt); pnl.add(endok); pnameok.addactionlistener(this); endok.addactionlistener(this); setdefaultcloseoperation(exit_on_close); setvisible(true); } public void actionperformed( actionevent event ) { if(event.getsource() == endok) { try { string end = endtxt.gettext(); filewriter endfile = new filewriter( end + ".txt" ); } catch( ioexception e ) { boolean uselessend = true; } if(event.getsource() == pnameok) { try { string pname = progname.gettext(); filewriter pnamefile = new filewriter( pname + ".txt" ); } catch( ioexception e1 ) { boolean uselesspname = true; try { filewriter pnamefileuse = new filewriter( "error" ); } catch( ioexception e2 ) { boolean completeandutterfail = true; } } } } } }
when run it, enter yay
program name , exe
type of file , click both of ok buttons, new file called exe.txt
no file called yay.txt
. why this?
yes. have done stupid. , there mess of curly brackets over. remove end bracket (}
) end , add after code:
catch( ioexception e ) { boolean uselessend = true; }
so becomes this:
catch( ioexception e ) { boolean uselessend = true; } }
that should fix it. sidenote: 1. make first letter of class name capital. (e.g. plugin
). 2. indent code better readibility. 3. might want add e.printstacktrace()
debugging in catch
part of exceptions.
Comments
Post a Comment