Java JTextArea实时输出

Java JTextArea实时输出,java,swing,jtextarea,Java,Swing,Jtextarea,您好,我已经创建了一个循环等待队列模拟,并且我已经向GUI说明了问题所在,当用户单击run按钮时,在10-15秒的时间内没有显示任何内容,然后整个输出显示在JTextArea中。如何像在控制台中一样输出附加到jtextarea的所有内容。我查了一个叫SwingWorker的东西。但我不知道如何使用它。请帮忙 package Windows; import java.awt.Container; import java.awt.Dimension; import java.awt.GridLayo

您好,我已经创建了一个循环等待队列模拟,并且我已经向GUI说明了问题所在,当用户单击run按钮时,在10-15秒的时间内没有显示任何内容,然后整个输出显示在JTextArea中。如何像在控制台中一样输出附加到jtextarea的所有内容。我查了一个叫SwingWorker的东西。但我不知道如何使用它。请帮忙

package Windows;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;


public class Station implements  ActionListener 
{
    private JTextArea userinput, useroutput;
    private JScrollPane sbr_userinput, sbr_useroutput;
    private JButton runButton, clearButton, homeButton;

    //LinkedList Customer Queue created here.
    public static Queue<String> line = new  LinkedList<String> ();
    private static String time;   //time variable.
    private static DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");   //DateFormat variable.

    private int intervals;
    private int cashiers;
    private int processing_time;

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

    public Station()
    {
        JFrame frame = new JFrame("[=] Train Station Simulation [=]");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(800, 400);

        frame.setContentPane(GUI());

        frame.setVisible(true);
    }

    public Container GUI() 
    {
        JPanel totalGUI = new JPanel();
        totalGUI.setLayout(new GridLayout(1, 2, 3, 3));

        JPanel lPanel = new JPanel();
        lPanel.setLayout(new GridLayout(2, 1, 3 , 3));
        totalGUI.add(lPanel);

        JPanel rPanel = new JPanel(new GridLayout(3, 1, 3 , 3));
        totalGUI.add(rPanel);

        userinput = new JTextArea("Welcome to Train Station Queue Simulation!!!" + "\n" + 
        "Enter the number of cashiers available HERE!!!!:" + "\n");
        userinput.setEditable(true);
        userinput.setLineWrap(true);
        userinput.setWrapStyleWord(true);
        lPanel.add(userinput);

        useroutput = new JTextArea();
        useroutput.setEditable(false);
        useroutput.setLineWrap(true);
        useroutput.setWrapStyleWord(true);
        lPanel.add(useroutput);

        sbr_userinput = new JScrollPane(userinput, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        sbr_userinput.setPreferredSize(new Dimension(300, 300));
        lPanel.add(sbr_userinput);

        sbr_useroutput = new JScrollPane(useroutput, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
                JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        sbr_useroutput.setPreferredSize(new Dimension(300, 300));
        lPanel.add(sbr_useroutput);

        runButton = new JButton("RUN");
        runButton.addActionListener(this);
        rPanel.add(runButton);

        clearButton = new JButton("CLEAR");
        clearButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                userinput.setText("");
                useroutput.setText("");
                System.out.println("cleared");
            }
        });
        rPanel.add(clearButton);

        homeButton = new JButton("HOME");
        rPanel.add(homeButton);

        totalGUI.setOpaque(true);
        return totalGUI;
    }

    public void actionPerformed(ActionEvent e)
    {
        cashiers = Integer.parseInt(userinput.getText());
        if (e.getSource() == this.runButton)
        {
            useroutput.append("CUSTOMERS ARE COMING !!!! !!!!" + "\n" + "\n");;

            //Array of all the customer that will enter the queue.
            String list[] = {"Naqi", "Monty", "Mohin", "Yasmin", "Maighjoo", "Ashish", "Paal", "Kevin", "Ruhail", "Tony"};
            //2nd ArrayList which customer are added to and removed later on so no duplicates arise.
            ArrayList<String> customer = new ArrayList<String>(Arrays.asList(list));

            int array_customer_list = list.length; //Recording the number of customers in the array.

            //While statement containing for loop add customers to the empty LinkedList object.
            while (line.isEmpty())
            {
                for (int x = 0; x < array_customer_list; x++ )
                {
                    try
                    {
                        Thread.sleep(ran_interval() * 1000);   //Sleep method to hold the arrival time by 1-2 seconds. 
                        int cus = (int) (Math.random() * customer.size());   //Random customer is picked here. 
                        String new_cus = customer.get(cus);   //New customer object is created ere.
                        line.add(new_cus);   //Customer objects are added to the empty LinkedList queue.
                        customer.remove(cus);

                        //For loop statement to outputting the queue.
                        for (String s : line)
                        {
                            useroutput.append("[" + s.toString() + " " + "]" + "\n");; //Outputting each customer and using the ".name" method so customers are readable.
                        }
                        //Outputting the whole queue and stating who has joined the queue.
                        useroutput.append("\n" + "The queue has " + line.size() + " customers so far" + "\n" + 
                        new_cus.toString() + " Has Joined the Queue " + " <=== WAITING" + "\n" + "\n");
                    }
                    catch(Exception a)   //ERROR handler for sleep method.
                    {
                        System.out.println("Intervals error: " + e);   //Outputting the ERROR message.
                        System.exit(0);   //If ERROR found exit system.
                    }

                }
            }

            userinput.append("\n");
            useroutput.append("CUSTOMERS ARE WAITING !!!! !!!!" + "\n" + "\n");
            useroutput.append("Processing START !!!!" + "\n" + "\n");

            while (!line.isEmpty())   //While statement with for loop to remove each customer from LinkedList queue.
            {
                try 
                {
                    String cus = line.remove(); //Method to remove customer from LinkedList queue.
                    String time = getTime();
                    Thread.sleep((processing_time() * 1000) / cashiers); //Sleep method to hold the processing by 1-3 seconds.
                    for (String s : line)
                    {
                        useroutput.append("[" + s.toString() + " " + "]" + "\n"); //Outputting each customer and using the ".name" method so customers are readable.
                    }
                    //Outputting the whole queue and stating who has joined the queue.
                    useroutput.append("\n" + "The queue has " + line.size() + " customers left" + "\n" + 
                    cus.toString()+ " waited for " + time + " <=== SERVED" + "\n" + "\n");
                }
                catch(Exception a)   //ERROR handler for sleep method.
                {
                    System.out.println("Cashiers_wait error: " + e);   //Outputting the ERROR message.
                    System.exit(0);   //If ERROR found exit system.
                }
            }
        }

        useroutput.append("Processing FINISHED !!!!" + "\n");
        System.out.println("working");
    }

    static String getTime()   //Time Constructor
    {
       Calendar cal = Calendar.getInstance();
       time = dateFormat.format(cal.getTime());   //Getting the current system time.
       return time;   //Return time.
    }

    public int ran_interval()
     {
         Random rand = new Random(); //Random object created here.
         int interval = this.intervals = rand.nextInt(2) + 1; //Random number between 1-2 is generated for customer arrival here.

         return interval;
     }

    public int processing_time()
     {
         Random ran = new Random();    //Random object created here.
         int time = this.processing_time = ran.nextInt(4) + 1;  //Random number between 1-3 is generated for customer arrival here.

         return time;
     }
}
包窗口;
导入java.awt.Container;
导入java.awt.Dimension;
导入java.awt.GridLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.text.DateFormat;
导入java.text.simpleDataFormat;
导入java.util.ArrayList;
导入java.util.array;
导入java.util.Calendar;
导入java.util.LinkedList;
导入java.util.Queue;
导入java.util.Random;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.JScrollPane;
导入javax.swing.JTextArea;
公共类站实现ActionListener
{
私有JTextArea用户输入、用户输出;
私有JScrollPane sbr_用户输入,sbr_用户输出;
私有JButton runButton、clearButton、homeButton;
//在此处创建的LinkedList客户队列。
公共静态队列行=新的LinkedList();
私有静态字符串时间;//时间变量。
private static DateFormat DateFormat=new SimpleDateFormat(“HH:mm:ss”);//DateFormat变量。
私有整数间隔;
私人收银员;
私有整数处理时间;
公共静态void main(字符串[]args)
{
新电台();
}
公共电台()
{
JFrame frame=新JFrame(“[=]火车站模拟[=]”);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
框架设置尺寸(800400);
frame.setContentPane(GUI());
frame.setVisible(true);
}
公共容器GUI()
{
JPanel totalGUI=新的JPanel();
setLayout(新的GridLayout(1,2,3,3));
JPanel lPanel=新的JPanel();
setLayout(新的GridLayout(2,1,3,3));
添加(lPanel);
JPanel rPanel=新的JPanel(新的网格布局(3,1,3,3));
totalGUI.add(rPanel);
userinput=new JTextArea(“欢迎来到火车站队列模拟!!!”+“\n”+
“在此处输入可用的出纳人数!!!!:”+“\n”);
userinput.setEditable(true);
setLineWrap(true);
setWrapStyleWord(true);
lPanel.add(用户输入);
useroutput=newjtextarea();
useroutput.setEditable(false);
setLineWrap(true);
setWrapStyleWord(true);
lPanel.add(useroutput);
sbr_userinput=新的JScrollPane(userinput,JScrollPane.VERTICAL_SCROLLBAR_根据需要,
JScrollPane.水平滚动条(根据需要);
sbr_userinput.setPreferredSize(新维度(300300));
lPanel.add(sbr\u用户输入);
sbr_useroutput=新的JScrollPane(useroutput,JScrollPane.VERTICAL_SCROLLBAR_根据需要,
JScrollPane.水平滚动条(根据需要);
sbr_useroutput.setPreferredSize(新维度(300300));
lPanel.add(sbr\u用户输出);
runButton=新的JButton(“RUN”);
runButton.addActionListener(这个);
rPanel.add(运行按钮);
clearButton=新的JButton(“CLEAR”);
clearButton.addActionListener(新ActionListener()
{
已执行的公共无效操作(操作事件e)
{
userinput.setText(“”);
useroutput.setText(“”);
系统输出打印项次(“已清除”);
}
});
rPanel.add(清除按钮);
homeButton=新的JButton(“HOME”);
rPanel.add(主页按钮);
set不透明(true);
返回totalGUI;
}
已执行的公共无效操作(操作事件e)
{
cashiers=Integer.parseInt(userinput.getText());
如果(e.getSource()==this.runButton)
{
追加(“客户来了!!!!”+“\n”+“\n”);;
//将进入队列的所有客户的数组。
字符串列表[]={“纳齐”、“蒙蒂”、“莫欣”、“雅斯敏”、“麦乔”、“阿什”、“帕尔”、“凯文”、“鲁海尔”、“托尼”};
//第二个ArrayList,客户随后将添加到该列表中并删除,因此不会出现重复。
ArrayList客户=新的ArrayList(Arrays.asList(list));
int array\u customer\u list=list.length;//记录数组中的客户数。
//包含for循环的While语句将客户添加到空LinkedList对象。
while(line.isEmpty())
{
对于(int x=0;xnew_cus.toString()+”已加入队列“+”执行此操作的一种方法是使用模型视图类型
Initialize UI
While program is running
    Wait for event (like action performed, or ready to update event)
    If button was pressed
        Add task to data model's work queue
    Else // Was not a button event, so therefore the data model must 
         // have sent an update
        Set values in GUI components using the updated data
        Repaint GUI
While model has work to do
    Work on next task // and manipulate data
    Send update event to GUI
frame.paint(frame.getGraphics());