GUI TextArea中的java for循环

时间:2013-08-20 09:56:25

标签: java swing user-interface for-loop textarea

问题非常简单....我有一个for循环来打印标题列表并将结果附加到GUI的TextArea。例如,列表包含标题A,B,C。每次TextArea都应逐一显示标题。但是,就我而言,打印输出始终显示整个标题列表。     我的TextArea方法在for循环中调用。它应该附加每个循环的打印输出,但不是整个列表。如何解决它请帮助...

抱歉让人困惑......我正在使用JTextArea来显示结果。这是代码:

    private static JTextArea textArea1;
 ....
 ....
    textArea1 = new JTextArea(26, 38);
    textArea1.setLineWrap(true);
    textArea1.setEditable(false);
    sbrText = new JScrollPane(textArea1);
    sbrText.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
....
....

public static void getStringText() {

    String ptime = passdata.getTime();
    String ppid = passdata.getPageid();
    String ptitle = passdata.getTitle();
    String previd = passdata.getrevid();
    String pparentid = passdata.getParentId();
    String puser = passdata.getUser();
    String pcomments = passdata.getComments();

    textArea1.append("Timestamp: " + ptime + "\n" + "Pageid: " + ppid
            + "\n" + "Title:" + ptitle + "\n" + "Revid:" + previd + "\n"
            + "Parentid:" + pparentid + "\n" + "User:" + puser + "\n"
            + "Comments:" + pcomments + "\n" + newline + newline);
    textArea1.setCaretPosition(textArea1.getDocument().getLength());
    // System.out.println(passToText.getPageid());
}

在for循环中调用getStringText()方法。

这是我构建的GUI。它显示标题及其信息,不能逐个打印,在for循环中,它应该像A一样打印,然后B.应该在GUI上显示A上的动画,然后显示B.但在我的情况下,它同时显示A,B,C ...对不起很难解释我所看到的......

here is the GUI I built

1 个答案:

答案 0 :(得分:6)

在没有证据的情况下,听起来你在事件调度线程的上下文中循环。

这意味着在退出循环(和方法)之前,JTextArea的内容不会更新到屏幕

Swing是一个单线程环境。事件调度线程负责处理绘制请求等。任何阻止此线程的东西都会阻止它处理绘画更新。

还要求您对UI所做的所有更新和交互都是在EDT的上下文中完成的......

你有几个选择......

您可以使用javax.swing.Timer,这将允许在常规基础上触发ActionEvent,这在EDT的上下文中触发。这意味着当计时器“等待”时,它不会阻止EDT ......

您可以使用SwingWorker,它允许您在后台线程中执行处理,但为您提供能力publish结果返回EDT和process这些更新在EDT中...

查看Concurrency in Swing了解详情

更新了示例

javax.swing.Timer充当一种循环(都是一个不受控制的循环)。每个时期,它都会触发。你需要像对待已经循环的另一个迭代一样对待并根据需要更新UI的状态......

enter image description here

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TextTimer {

    public static void main(String[] args) {
        new TextTimer();
    }

    public TextTimer() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public static final String[] TEXT = new String[]{
        "Why, you wanna tell me how to live my life?",
        "Who, are you to tell me if it's black or white?",
        "Mama, can you hear me? Try to understand.",
        "Is innocence the difference between a boy and a man?",
        "My daddy lived the lie, that's just the price that he paid",
        "Sacrificed his life, just slavin' away.",
        "",
        "Ohhh, if there's one thing I hang onto,",
        "That gets me through the night.",
        "I ain't gonna do what I don't want to,",
        "I'm gonna live my life.",
        "Shining like a diamond, rolling with the dice,",
        "Standing on the ledge, I show the wind how to fly.",
        "When the world gets in my face,",
        "I say, Have A Nice Day.",
        "Have A Nice Day",
        "",
        "Take a look around you; nothing's what it seems",
        "We're living in the broken home of hopes and dreams,",
        "Let me be the first to shake a helping hand.",
        "Anybody brave enough to take a stand,",
        "I've knocked on every door, on every dead end street,",
        "Looking for forgiveness,",
        "what's left to believe?",
        "",
        "Ohhh, if there's one thing I hang onto,",
        "That gets me through the night.",
        "I ain't gonna do what I don't want to,",
        "I'm gonna live my life.",
        "Shining like a diamond, rolling with the dice,",
        "Standing on the ledge, I show the wind how to fly.",
        "When the world gets in my face,",
        "I say, Have A Nice Day.",
        "Have A Nice Day.",
        "",
        "[Guitar Solo]",
        "",
        "Ohhh, if there's one thing I hang onto,",
        "That gets me through the night.",
        "I ain't gonna do what I don't want to,",
        "I'm gonna live my life.",
        "Shining like a diamond, rolling with the dice,",
        "Standing on the ledge, I show the wind how to fly.",
        "When the world gets in my face,",
        "I say, Have A Nice Day.",
        "Have A Nice Day.",
        "Have A Nice Day.",
        "Have A Nice Day.",
        "Have A Nice Day.",
        "",
        "When The world keeps trying, to drag me down,",
        "I gotta raise my hands, I'm gonna stand my ground.",
        "Well I say, Have A Nice Day.",
        "Have A Nice Day",
        "Have A Nice Day"
    };

    public class TestPane extends JPanel {

        private JTextArea ta;
        private int currentLine = 0;

        public TestPane() {

            setLayout(new BorderLayout());
            ta = new JTextArea(20, 40);
            add(new JScrollPane(ta));

            Timer timer = new Timer(500, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    String text = TEXT[currentLine];
                    ta.append(text + "\n");
                    ta.setCaretPosition(ta.getText().length());
                    currentLine++;
                    if (currentLine >= TEXT.length) {
                        ((Timer)e.getSource()).stop();
                    }
                }
            });
            timer.start();            
        }        
    }
}