java - Why is my output null everytime? -
java - Why is my output null everytime? -
hello have class opens jframe , takes in text. when seek getting text says null. everytime click button want system.out print text entered in textarea.
this first class :
public class filereader { filebrowser x = new filebrowser(); private string filepath = x.filepath; public string getfilepath(){ homecoming this.filepath; } public static void main(string[] args) { filereader x = new filereader(); if(x.getfilepath() == null){ system.out.println("string null."); } else { system.out.println(x.getfilepath()); } } }
this jframe takes in input , stores in static string.
/* * class used read location * of file user. */ import java.awt.*; import java.awt.event.*; import java.awt.event.*; import javax.swing.*; public class filebrowser extends jframe{ private jtextarea textarea; private jbutton button; public static string filepath; public filebrowser(){ super("enter file path add"); setlayout(new borderlayout()); this.textarea = new jtextarea(); this.button = new jbutton("add file"); add(this.textarea, borderlayout.center); add(this.button, borderlayout.south); setdefaultcloseoperation(jframe.exit_on_close); setsize(300, 100); setvisible(true); this.button.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { filepath = new string(textarea.gettext()); system.exit(0); } }); } }
but everytime run these programs
string null.
you mistaken way how jframes work. jframe not stall execution of code until closed. so, basically, code creates jframe , grabs filepath
variable in object, before user have perchance specified file.
so, solve this, move code outputs filepath stdout actionlistener
have. rid of system.exit()
call, , utilize dispose()
instead.
update: should have code actionlistener:
this.button.addactionlistener(new actionlistener() { @override public void actionperformed(actionevent e) { filepath = new string(textarea.gettext()); if(filepath == null){ system.out.println("string null."); } else { system.out.println(filepath); } dispose(); } });
and main method:
public static void main(string[] args) { filebrowser x = new filebrowser(); }
java swing
Comments
Post a Comment