在GUI TextArea中的java for-loop [英] java for-loop in GUI TextArea

查看:145
本文介绍了在GUI TextArea中的java for-loop的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题很简单....我有一个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 +\\\
+Pageid:​​+ ppid
+\\\
+标题:+ ptitle + \\\
+Revid:+ previd +\\\

+Parentid:+ pparentid +\\\
+User:+ puser +\\\

+注释:+ pcomments +\\\
+ newline + newline);
textArea1.setCaretPosition(textArea1.getDocument()。getLength());
// System.out.println(passToText.getPageid());
}

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



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



解决方案

如果没有证据的话,这听起来像是在事件分派线程的上下文中循环。

这意味着直到你退出循环(和方法), JTextArea 的内容将不会更新到屏幕上。

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



所有更新和交互都是从UI的上下文EDT ...

您有几个选项...

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

您可以使用 SwingWorker ,它允许您在后台线程中执行处理,但是可以将 publish 结果返回到EDT和进程 code>这些更新在EDT ...



查看在Swing中的并发性了解更多详细信息

用示例更新

javax.swing.Timer 作为循环的一种(全部是一个不受控制的循环)。每个时期都会触发。你需要对待,就像你刚刚循环另一个迭代,并根据需要更新UI的状态... ...

stack.imgur.com/TLRqM.pngalt =

pre $ 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();

$ b $ public TextTimer(){
EventQueue.invokeLater(new Runnable(){
@Override
public void run(){
尝试{
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 [] {
为什么你要告诉我如何过我的生活?,
你是谁,告诉我它是黑色的还是白色的?,
妈妈,你能听到我吗?试着理解。,
无辜是男孩还是男人的区别? ,
我爸爸住的谎言,那只是他付出的代价,
牺牲了他的生命,就这样一瘸一拐地离开了。,

Ohhh ,如果有一件事我会坚持,
这让我度过了一夜。,
我不会做我不想做的事,
我要过上我的生活,
像钻石一样闪闪发光,用骰子滚动,
站在窗台上,我展示风如何飞翔,
当世界进入我的面前,
我说,祝你有美好的一天,
祝你有美好的一天,

看看你,什么也没有我们生活在希望和梦想的破碎之家,
让我成为第一个握手的人,
任何人都可以站出来,
我在每一条死路上敲开了每一扇门,
寻找原谅,
还剩下什么?相信吗?,

哦,如果有一件事情我会坚持下去的,
这让我度过了一夜。,
I ain' b $ b我要过上我的生活,
像钻石一样闪闪发亮,用骰子滚动,
站在窗台上,我展示了如何飞翔的风。,
当世界进入我的脸时,
我说,祝你有美好的一天,
祝你有个美好的一天,

[吉他独奏],

哦,如果有一件事情我要挂上 b $ b让我度过ni ght。,
我不会做我不想做的事,
我要过上我的生活,
像钻石一样闪耀,骰子滚动,
站在窗台上,我会展示风如何飞翔。,
当世界进入我的脸时,
我说,祝你有美好的一天,
祝你有美好的一天,
祝你有美好的一天,
祝你有美好的一天,
美好的一天,

当世界不断尝试,把我拉下来,
我必须举起双手,我要站在我的立场上。 ,
我说,祝你有美好的一天,
祝你有美好的一天,
祝你有美好的一天
;

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

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


the question is really simple....I have a for loop to print a list of titles and append the results to the TextArea of GUI. for example the list contains titles A, B, C. Every time the TextArea should display the titles one by one. But, in my case, the print-out is always shows the whole list of titles. My TextArea method is called inside the for loop. it should be appended the print-out for each loop but not entire list. how to solve it please help...

sorry for the confusing...I am using JTextArea to show the results. here is the code:

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

the getStringText() method is called inside a for loop.

here is the GUI i built. it shows the title with its information, cannot be print one by one means, in the for loop, it should be printed like A, and then B. the animation on the GUI should be shown A and then shown B. But in my case, it shows A,B, C at the same time...Sorry It hard to explain what I am seeing....

解决方案

With out evidence to the contrie, it sounds like you're looping within the context of the Event Dispatching Thread.

This means that until you exit the loop (and the method), the contents of the JTextArea won't be updated to the screen

Swing is a single threaded environment. The Event Dispatching Thread is responsible for, amongst other things, processing paint requests. Anything that blocks this thread will prevent it from processing painting updates.

It is also required that all updates and interactions you make to the UI are done from within the context of the EDT...

You have a couple of options...

You could use a javax.swing.Timer, which will allow to trigger an ActionEvent on a regular bases, which is triggered within the context of the EDT. This means that while the timer is "waiting", it won't block the EDT...

You could use a SwingWorker, which allows you perform processing in a background thread, but provides you with the ability publish results back to the EDT and process these updates within the EDT...

Check out Concurrency in Swing for more details

Updated with example

javax.swing.Timer acts as kind of loop (all be it an uncontrolled loop). Every period, it will trigger. You need to treat as if you have just looped another iteration and update the state of the UI as required...

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

这篇关于在GUI TextArea中的java for-loop的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆