我在这里找到了这段代码:how to display console output in java JTextarea in a loop when button action is triggered and it display console output in a jtextarea. 我已将此类添加为 jmenuitem 中的操作。这样它就会在我想要的时候出现,当我运行其他类时它会在那里显示输出。但是,当我启动它时,它可以正常工作,但是如果我尝试启动另一个将在控制台中显示输出并接受用户输入的类,则应该同时显示控制台输出的 jtextarea 会冻结。尽管调用了其他类/框架,我怎样才能使它保持调整?提前致谢
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DynamicWrite implements ActionListener
{
JFrame frame = new JFrame("TextArea");
JTextArea tArea = new JTextArea(10,20);
JButton button = new JButton("Click");
JScrollPane pane = new JScrollPane(tArea);
SwingWorker worker;
String s= "Java is an Object Oriented Programming langauge...Java is static typed language...asbfldfjsdj";//some random String
public void prepareAndShowGUI()
{
Container container = frame.getContentPane();
container.add(pane);container.add(button,BorderLayout.NORTH);
tArea.setLineWrap(true);
tArea.setWrapStyleWord(true) ;
button.addActionListener(this);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
if(evt.getSource()==button)
{
tArea.setText("");
if (worker!=null)
{
worker.cancel(true);
}
worker = new SwingWorker()
{
@Override
protected Integer doInBackground()//Perform the required GUI update here.
{
try
{
for(int i = 0;i<s.length();i++)
{
tArea.append(String.valueOf(s.charAt(i)));
Thread.sleep(5);
}
}catch(Exception ex){}
return 0;
}
};
worker.execute();//Schedules this SwingWorker for execution on a worker thread.
}
}
public static void main(String st[])
{
DynamicWrite dyna = new DynamicWrite();
dyna.prepareAndShowGUI();
}
}