Problem with JTextArea when printing

0

I have the following code that writes a text in the JtextArea, waits 3 seconds and deletes it. My problem is that the code does not get to write the first text.

bb.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent e){

        pantalla.setText("Usted borrará la pantalla en 3 segundos!!");

        System.out.println(pantalla.getText());

        Date hora = new Date();
        hora.getTime();
        while(System.currentTimeMillis() < (hora.getTime() + 3000)){
        }
        if (pantalla.getText().equals(new String("Usted borrará la pantalla en 3 segundos!!"))){
        pantalla.setText("");
        System.out.print(1);
        }
        System.out.print("llegue");


    }
});
    
asked by Brais Castiñeiras Galdo 11.07.2017 в 14:22
source

1 answer

0

The GUI events are treated in the Thread of "Event Dispatch", which is also responsible for repainting the screen. Here is more information (in English, of course).

In other words, while the code associated with the event is being processed, the screen will not be refreshed. It refreshes once you have left, but obviously with the value "" in TextArea .

This is what happens when, for example, you try to execute a logic that takes a long time and the GUI is "frozen".

The solution is, both in your case and in the case of frozen GUI, to launch the logic in a separate thread. There may be better forms ( ExecutorService and similar), but the fastest is:

public void actionPerformed(ActionEvent e){

        Thread thread = new Thread() {
            @Override
            public void run() {
               NombreSuperClase.this.pantalla.setText("Usted borrará la pantalla en 3 segundos!!");

               System.out.println(pantalla.getText());

               Date hora = new Date();
               hora.getTime();
               while(System.currentTimeMillis() < (hora.getTime() + 3000)){
                  synchronized(this) { //Evitar bucles vacíos!!!
                      this.wait(500);
                  }
                }

                if (pantalla.getText().equals(new String("Usted borrará la pantalla en 3 segundos!!"))){
                    pantalla.setText("");
                    System.out.print(1);
                 }
                 System.out.println("Llegué!");
             }
         }
         thread.start();
         System.out.print("thread lanzado");
      }

By the way, I insist again that empty loops are very bad thing ... better to put wait in the middle, even if they are brief, so that they do not saturate the CPU (there is not much problem for a thread in an infinite loop , but if you do things wrong you'll end up doing it badly always and with 200 threads eating the processor).

    
answered by 11.07.2017 / 14:56
source