java - Printing output on textfield -
can me? question how can print output inside textfield?
system.out.print("enter sentence"); word = input.nextline(); word= word.touppercase(); string[] t = word.split(" "); (string e : t) if(e.startswith("a")){ jframe f= new jframe ("output"); jlabel lbl = new jlabel (e); f.add(lbl); f.setsize(300,200); f.setvisible(true); f.setdefaultcloseoperation(jframe.exit_on_close); f.setlocationrelativeto(null);
the code posted make crazy things: creating , showing new frame every time find string starting "a". should create frame just once, example can prepare output before creating frame concatenating desidered elements of 't' array. create frame adding jtextfield desired text. might prefer have output printed in different lines textarea. if use textarea can use append method (look example below).
remember
setvisible(true)
should last instruction when create jframe, or have undesired behaviour, if try add components frame after calling it. also, it's better call pack() method on jframe setting size manually.
look example below see how solve problem :
import java.util.scanner; import javax.swing.jframe; import javax.swing.jtextarea; import javax.swing.jtextfield; import javax.swing.swingutilities; public class test { public static void main(string[] a) { system.out.print("enter sentence"); scanner input = new scanner(system.in); string word = input.nextline().touppercase(); string[] t = word.split(" "); swingutilities.invokelater(new runnable() { public void run() { string separator = system.lineseparator(); // decide here string used separate output, can use "" if don't want separate different parts of array 't' jframe f = new jframe ("output"); // first solution: use jtextarea jtextarea textarea = new jtextarea(); textarea.seteditable(false); // might want turn off possibilty change text inside textarea, comment out line if don't textarea.setfocusable(false); // might want turn off possibility select text inside textarea, comment out line if don't (string e : t) if(e.startswith("a")) textarea.append(e + separator); f.add(textarea); // second solution: if still want have output textfield, replace previous 5 lines of code following code : // separator = " "; // in case don't use newline separate output // string text = ""; // (string e : t) if(e.startswith("a")) text += e + separator; // f.add(new jtextfield(text)); // f.setsize(300,200); f.setdefaultcloseoperation(jframe.exit_on_close); f.pack(); f.setlocationrelativeto(null); f.setvisible(true); } }); } }
Comments
Post a Comment