JTextArea real time output

后端 未结 2 425
名媛妹妹
名媛妹妹 2021-01-24 19:30

Hi I have created a waiting queue simulation with loops and also I have made the GUI what the problem is when the user clicks the run button nothing shows up for couples of seco

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-24 20:02

    One way you can do this is using the model-view type of program design. Basically, you have 2 threads: one that handles the GUI (view/controller), and a second thread that manipulates the data (model). When an action is performed in the GUI, you start the second thread and tell it to go muck with the data. Then, as the data model thread starts changing values, it tells the GUI thread to go update the GUI by sending an event of some sort.

    For more about the Model-View-Controller design, see http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

    In pseudo code, here's how this would work:

    GUI Thread

    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
    

    Data Model Thread (usually has a work queue that the GUI thread can use to tell it what to do)

    While model has work to do
        Work on next task // and manipulate data
        Send update event to GUI
    

    As you can see, this is easier to implement if you incorporate this idea from the start.

    Another way to "fix" this issue is to plant this call whenever you want the UI to update instantly:

    frame.paint(frame.getGraphics());
    

    HOWEVER, this is a hack, as JFrame.paint and JFrame.getGraphics are both internal Swing methods, and so this should not be used unless you have no other choice. If you call this too frequently, it does create a nasty flickering effect/screen tearing, as you are updating the pixel data at the exact same time as the computer is sending that pixel data to the monitor for display. (Most computers do this about 30-60 times per second.)

提交回复
热议问题