在文本字段上打印输出

时间:2016-11-13 09:35:39

标签: java swing jframe jlabel jtextfield

有人能帮助我吗?我的问题是如何在文本字段中打印所有输出?

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);

1 个答案:

答案 0 :(得分:0)

您发布的代码会让您发疯:您正在创建并显示一个新框架每次您找到一个以“A”开头的字符串。 你应该创建一个一次的框架,例如你可以在创建框架之前通过连接't'数组的desidered元素来准备输出。 然后创建框架,添加带有所需文本的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);
            }
        });
    }
}