2016-11-13 63 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); 
      } 
     }); 
    } 
}