2016-11-13 62 views
-1

有人可以帮助我吗?我的问题是如何在文本框内打印所有输出?在文本框上打印输出

System.out.print("Enter sentence"); 
word = input.nextLine(); 
word= word.toUpperCase(); 

String[] t = word.split(" "); 

for (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); 
+0

创建'JTextField'和使用方法'的setText(文字);' – GOXR3PLUS

回答

0

您发布将使疯狂的事情代码:要创建并显示每次一个新的帧你找到以“A”的字符串。 您应该只创建一个框架,例如,您可以在创建框架之前通过连接't'数组的描述元素来准备输出。 然后,您创建添加一个带有所需文本的JTextField的框架。您可能希望将输出以不同的行打印到textarea中。 如果你使用textarea,你也可以使用append方法(请看下面的例子)。

记住

setVisible(true) 

应该是最后的指令,当你创建一个JFrame,或者你可以有不期望的行为,特别是如果你尝试调用它之后将组件添加到帧。 另外,最好在JFrame上调用pack()方法,而不是手动设置大小。

请看下面的例子就看你如何能解决你的问题:

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 the string used to separate your output, you can use "" if you don't want to separate the different parts of the array 't' 
       JFrame f = new JFrame ("Output"); 
       // First solution: use a JTextArea 
       JTextArea textArea = new JTextArea(); 
       textArea.setEditable(false); // you might want to turn off the possibilty to change the text inside the textArea, comment out this line if you don't 
       textArea.setFocusable(false); // you might want to turn off the possibility to select the text inside the textArea, comment out this line if you don't 
       for (String e : t) if(e.startsWith("A")) textArea.append(e + separator); 
       f.add(textArea); 
       // Second solution: If you still want to have all the output into a textfield, replace the previous 5 lines of code with the following code : 
       // separator = " "; // in this case don't use a newline to separate the output 
       // String text = ""; 
       // for (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); 
      } 
     }); 
    } 
}