I make a Java application in NetBeans. It is necessary to output certain data obtained in the course of the program in the jTextArea field.

There is a main class A (with the main method), in which several buttons and one text field jTextArea created using the visual editor. By clicking on the button, one of the methods of class B is called, which performs certain actions and gives several results in the form of strings along the way.

It is necessary to display these results in jTextArea. Tried to do so A.jTextArea1.append("\nзначение");

But the problem is that the values ​​in jTextArea1 appear only after ALL actions in class B are completed (and the program returns to class A). This is logical, but I need to display the values ​​in jTextArea in real time, i.e. as soon as they appear.

How to implement it? I would be grateful for the help, or for the link to the explanatory material on this issue.

    1 answer 1

    Try wrapping a call to your method from class B to a stream. For example:

      /** * Метод, в котором выполняются все изменения area * * @param area элемент */ public void dosomething(final JTextArea area) { //Создаем поток new Thread(new Runnable() { /** * Переопределяем метод run, который и выполняется пр запуске потока */ @Override public void run() { try { //Добавляем текст "One" area.append("One"); //Задержка текущего потока 2 млс, чтобы не сразу появился сле.текст Thread.sleep(2000L); //Добавляем текст "Two" area.append("Two"); //Задержка текущего потока 2 млс, чтобы не сразу появился сле.текст Thread.sleep(2000L); //Добавляем текст "Three" area.append("Three"); //Задержка текущего потока 2 млс, чтобы не сразу появился сле.текст Thread.sleep(2000L); } catch (InterruptedException ex) { //Если что-то произошло при задержке(Thread.sleep) пишем в консоль Logger.getLogger(B.class.getName()).log(Level.SEVERE, null, ex); } } }).start();//Непосредственно запуск потока } 

    Well, the call on the button, respectively:

     new B().dosomething(jTextArea1); 
    • Thank you for the answer, I will use this method. I am new to Java, could you please add comments to the code, otherwise I don’t really understand how it works ... - andrshpa
    • I don’t even know what to sign (What exactly is not clear? If it works, then everything is simple: your application runs in a stream. By default. You just don’t see it. And what did we do? Right. They started a parallel stream to which they passed performance of functions. That is, you work in the main thread. You have started the parallel one in the "background" mode and continue to work mainly. And the parallel one works by itself already. And does not interfere with you) - Chubatiy
    • I understood everything already, thank you very much! - andrshpa
    • not at all) Comments added - Chubatiy