Break java loop

Asked

Viewed 508 times

3

My project in Java is a lighthouse control with Arduino. Up to there everything right. However I made a function in which the leds is automatic in a loop after a RadionButton be selected. My problem is that when I select the RadionButton mine JFrame freeze and don’t let me take out the selection of RadionButton.

In other words, selecting the button causes an active loop. The idea would be to uncheck the button, stop the loop.

Follows my code.

Here is where the button will be selected and send the command to the function:

        if ( teste.isSelected() ) {
        try {
            utiArduino.enviarDados( "automatico" );
        } catch (InterruptedException | IOException ex) {
            Logger.getLogger(Jframe_farol.class.getName()).log(Level.SEVERE, null, ex);
        }
    } else {
        try {
            utiArduino.enviarDados( "DesligaAuto" );
        } catch (InterruptedException | IOException ex) {
            Logger.getLogger(Jframe_farol.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Here is the function of the loop:

  public void enviarDados(String status) throws InterruptedException, IOException{
   int i = 8;

    if ( "automatico".equals(status) ) { // caso do automatico   
        while ( true ) {
            output.write(i);
            Thread.sleep(1000);
            i++;
            if ( i > 10 ){
                i = 8;
            }
        }
    }
} 
  • Read this: http://answall.com/a/2095/132 - This one Thread.sleep(1000) should be done on the AWT thread.

  • In addition to what @Victorstafusa said, I also think the approach of checking if the component is set to interrupt the loop is not correct, there are listeners to do this kind of monitoring. It only becomes difficult until you suggest an alternative with the snippet of past code.

1 answer

2


AWT and Swing have a thread that manages their operation, it is called Event Dispatch Thread - EDT. As she is a unique thread, if you make her fall into a while (true) and/or in a Thread.sleep(1000), the graphical interface will be frozen.

So the solution is to move these things to a distinct thread. Try doing so in your class utiArduino:

private volatile String ultimoStatus;
private volatile Thread threadArduino;

public void enviarDados(String status) {
   ultimoStatus = status;
   if (threadArduino == null) {
       threadArduino = new Thread(this::iniciarEnvioArduino);
       threadArduino.start();
   }
}

private void envioArduino() {
    int i = 8;
    try {
        while (Thread.currentThread() == threadArduino) {
            if ("automatico".equals(ultimoStatus)) { // caso do automatico   
                output.write(i);
                Thread.sleep(1000);
                i++;
                if (i > 10) i = 8;
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        // Não faz nada e deixa a thread morrer.
    }
}

public void parar() {
    if (threadArduino != null) {
        Thread t = threadArduino;
        threadArduino = null;
        t.interrupt();
    }
}

Your button selection looks like this:

utiArduino.enviarDados(teste.isSelected() ? "automatico" : "DesligaAuto");

In his subclass of JFrame (who assumes to be the one with the reference utiArduino), put this too:

@Override
public void dispose() {
    super.dispose();
    utiArduino.parar();
}

For more information on EDT, read in that my other answer also.

  • First of all Thank you for having answered my question , But the solution you answer , is with some errors, first in this excerpt of code ' super.Device();' ta with following error 'cannot find Symbol Symbol: method Dispose()' , the next error is on the line 'threadArduino = new Thread(this::startnvioArduino);' , this with the following error, 'method References are not supported in -source 1.7 (use -source 8 or Higher to enable method References) method Reference not expected here' and the method shipArduino() is not being used Can you help me? PLEASE

  • @Jeffersonsantos What class contains the variable utiArduino? What is the type of this variable? Your first mistake indicates that it was not the classes I was imagining they were, but that is not clear in your question. The second problem is something of a configuration, because it means that you are using the Java 8 compiler to compile Java 7, not compile Java 8 even, and my code is Java 8. Edit the question to complement it with this information.

  • Obg I will edit the question, but @Vitcorstafuses utiArduin is not a variable is the name of the class that contains the sent methodDados, but I will edit the question

  • @Jeffersonsantos The class utiArduino has any superclass? If yes, which one? What is the class that contains the call utiArduino.enviarDados( "automatico" );?

  • Boa noite @VictorStafusa a 'utiArduino' é uma classe simples nela contem a conexão , e o metodo utiArduino.enviarDados( "automatico" ); , ou seja no meu Jframe principal eu instancio essa classa e ultilizo o método utiArduino.enviarDados( "automatico" ); sorry the way you try explains the problem, would you help me?

  • @Jeffersonsantos The call utiArduino.enviarDados( "automatico" ); is within a class that inherits from JFrame? If so, what is her name?

  • @Jeffersonsantos I edited the answer. See if it works. If it doesn’t, explain to me what went wrong.

  • OI Vitor obg for take your time to help me, but the error you are giving now is about configuration even you had measured you know to do this or rot where I start the fabor?

  • @Jeffersonsantos As for configuration, it depends on whether you’re using Netbeans, Eclipse or something else. But in this case, I recommend you to create a new question about this configuration problem, because that would already be a very different problem than the one you presented in this question here, besides being something that you will find more people able to answer quickly.

Show 4 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.