Ciclo de Semáforo

Iniciado por Ubadelphis, 20 Octubre 2020, 02:58 AM

0 Miembros y 1 Visitante están viendo este tema.

Ubadelphis


Este es un fragmento de un programa en NetBeans, para carreras de Carros, ya lo terminé,
pero me falta el control del semáforo para el inicio de la carrra.
Tengo lo colores en un enum con la secuencia Rojo, Amarillo y Verde
Con una JLabel que muestra loas imágenes del semáforo para cada color.
El Problema es que No Consigo que el ciclo muestre la secuencia correcta, es decir Rojo, Amariilo y Verde,
que es cuando se inicia la carrera, además me debería mostrar en el texto de la JLabel,
lo siguinete: Esperar y el conteo del Tiempo en segundos, para el color Rojo, Preparados y el conteo del Tiempo en segundos
para el Color Amarillo y finalmente Cambiar a verde y mostrar en el texto de la Jlabel Partida y la Cuenta Final de los Segundos
Creo, que con tiempo de 5 segundos (5000 milisegundos) desde el color Rojo mas otros 5 segundos para el color Amarillo y 15 segundos
como cuenta final para el verde y así iniciar la carrera que está diseñada con hilos, uno para cada corredor.
Actualemnte pasa de Rojo a Aamrillo y se inicia la carrera o pasa de rojo a verde y se inicia la carrera, pero no me muestra el amarillo.
He Probado varias formas pero no doy con el código corecto, gracias de antemano por su atención,

Código (java) [Seleccionar]
for(int i=3; i>0; i--)
{
 System.out.println(i);
        // jSemaforo.setText("Esperar"+i);
  try
    {                                                  
     Thread.sleep(3000);
             
             if (i==3)
              {
                 Imagenes = new ImageIcon(getClass().getResource("rojo.jpg"));  
                 jSemaforo.setIcon(Imagenes);
                 jSemaforo.setText("Esperar"+i);
              }
             else
             {
                 if (i==2)
                    {
                     Imagenes = new ImageIcon(getClass().getResource("amarillo.jpg"));  
                      jSemaforo.setIcon(Imagenes);
                      jSemaforo.setText("Preparados"+i);
                     }
                   else
{
        if (i==3)
                       {
                        Imagenes = new ImageIcon(getClass().getResource("verde.jpg"));  
                        jSemaforo.setIcon(Imagenes);
                        jSemaforo.setText("Partidas"+i);
                       }
 }
 }  
             
    }  catch(InterruptedException e){}





Mod: Obligatorio el uso de etiquetas GeSHi para código.

rub'n

Pasa el codigo mas completo creo que fallas en el condicional.


rubn0x52.com KNOWLEDGE  SHOULD BE FREE!!!
If you don't have time to read, you don't have the time (or the tools) to write, Simple as that. Stephen

Ubadelphis

#2
Gracias por Responder, aquí va mas código, se refiere al JFrameAuto.java
package carreraautos;

Código (java) [Seleccionar]
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;



/**
*
* @author conej
*/
public class JframeAuto extends javax.swing.JFrame {
   public enum ColorSemaforo {
Rojo, Ambar, Verde;
}
   

   /**
    * Creates new form JframeAuto
    */
   public JframeAuto() {
       initComponents();
   }
   public JLabel getlbl1(){
       return lbl1;
   }
   public JLabel getlbl2(){
       return lbl2;
   }
   public JLabel getlbl3(){
       return lbl3;
   }
   public JLabel getlbl_barrera(){
       return lbl_barrera;
   }

   /**
    * This method is called from within the constructor to initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is always
    * regenerated by the Form Editor.
    */
   @SuppressWarnings("unchecked")
   // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
   private void initComponents() {

       jPanel1 = new javax.swing.JPanel();
       lbl1 = new javax.swing.JLabel();
       lbl2 = new javax.swing.JLabel();
       lbl_barrera = new javax.swing.JLabel();
       lbl3 = new javax.swing.JLabel();
       jSemaforo = new javax.swing.JLabel();
       jLabel1 = new javax.swing.JLabel();
       btiniciar = new javax.swing.JButton();

       setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

       jPanel1.setBackground(new java.awt.Color(102, 255, 102));
       jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

       lbl1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
       lbl1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/carreraautos/Corredor_Azul.jpg"))); // NOI18N
       lbl1.setText("1");

       lbl2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
       lbl2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/carreraautos/Corredor_Naranja.jpg"))); // NOI18N
       lbl2.setText("2");
       lbl2.setName(""); // NOI18N

       lbl_barrera.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 51), 10));

       lbl3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
       lbl3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/carreraautos/Corredor_Negro.jpg"))); // NOI18N
       lbl3.setText("3");

       jSemaforo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
       jSemaforo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/carreraautos/rojo.jpg"))); // NOI18N
       jSemaforo.setText("Partida");

       javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
       jPanel1.setLayout(jPanel1Layout);
       jPanel1Layout.setHorizontalGroup(
           jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(jPanel1Layout.createSequentialGroup()
               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                   .addGroup(jPanel1Layout.createSequentialGroup()
                       .addContainerGap()
                       .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                           .addComponent(lbl2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                           .addComponent(lbl3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                           .addComponent(lbl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                   .addGroup(jPanel1Layout.createSequentialGroup()
                       .addGap(20, 20, 20)
                       .addComponent(jSemaforo)))
               .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(lbl_barrera)
               .addContainerGap())
       );
       jPanel1Layout.setVerticalGroup(
           jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(jPanel1Layout.createSequentialGroup()
               .addGap(18, 18, 18)
               .addComponent(lbl1)
               .addGap(39, 39, 39)
               .addComponent(lbl2)
               .addGap(26, 26, 26)
               .addComponent(lbl3, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addGap(66, 66, 66)
               .addComponent(jSemaforo)
               .addContainerGap(59, Short.MAX_VALUE))
           .addComponent(lbl_barrera, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
       );

       jLabel1.setText("Carrera de Autos");

       btiniciar.setText("Iniciar Carrera");
       btiniciar.addActionListener(new java.awt.event.ActionListener() {
           public void actionPerformed(java.awt.event.ActionEvent evt) {
               btiniciarActionPerformed(evt);
           }
       });

       javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
       getContentPane().setLayout(layout);
       layout.setHorizontalGroup(
           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(layout.createSequentialGroup()
               .addContainerGap()
               .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                   .addGroup(layout.createSequentialGroup()
                       .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                       .addContainerGap())
                   .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                       .addGap(0, 439, Short.MAX_VALUE)
                       .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
                       .addGap(97, 97, 97))))
           .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
               .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addComponent(btiniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
               .addGap(273, 273, 273))
       );
       layout.setVerticalGroup(
           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(layout.createSequentialGroup()
               .addGap(4, 4, 4)
               .addComponent(jLabel1)
               .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
               .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
               .addComponent(btiniciar)
               .addGap(36, 36, 36))
       );

       pack();
   }// </editor-fold>                        

   private void btiniciarActionPerformed(java.awt.event.ActionEvent evt) {                                          
       
       lbl1.setLocation(0,lbl1.getLocation().y);
       lbl2.setLocation(0,lbl2.getLocation().y);
       lbl3.setLocation(0,lbl3.getLocation().y);
       Carrera hilo1=new Carrera(lbl1, this);
       Carrera hilo2=new Carrera(lbl2, this);
       Carrera hilo3=new Carrera(lbl3, this);
     
    long inicio;
     inicio=System.currentTimeMillis()/1000;
     System.out.println("segundo: " + inicio);  
       Icon Imagenes;  
       
       Semaforo misemaforo=new Semaforo();
               
       int c=0;
           
     
     for(int i=3; i>0; i--)
  {
    System.out.println(i);
        // jSemaforo.setText("Esperar"+i);
     try
       {                                                
        Thread.sleep(3000);
           
             if (i==3)
              {
                 Imagenes = new ImageIcon(getClass().getResource("rojo.jpg"));
                 jSemaforo.setIcon(Imagenes);
                 jSemaforo.setText("Esperar"+i);
              }
             else
             {
                 if (i==2)
                    {
                     Imagenes = new ImageIcon(getClass().getResource("amarillo.jpg"));
                      jSemaforo.setIcon(Imagenes);
                      jSemaforo.setText("Preparados"+i);
                     }
                   else
        {
              if (i==3)
                       {
                        Imagenes = new ImageIcon(getClass().getResource("verde.jpg"));
                        jSemaforo.setIcon(Imagenes);
                        jSemaforo.setText("Partidas"+i);
                       }
                }
          }                
             
       }  catch(InterruptedException e){}

          {
           Imagenes = new ImageIcon(getClass().getResource("verde.jpg"));  
           jSemaforo.setIcon(Imagenes);
           }
}
     
     
       hilo1.start();
       hilo2.start();
       hilo3.start();
                   
   
     
         
   }                                        

   
   public static void main(String args[]) {
     
       try {
           for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
               if ("Nimbus".equals(info.getName())) {
                   javax.swing.UIManager.setLookAndFeel(info.getClassName());
                   break;
               }
           }
       } catch (ClassNotFoundException ex) {
           java.util.logging.Logger.getLogger(JframeAuto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       } catch (InstantiationException ex) {
           java.util.logging.Logger.getLogger(JframeAuto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       } catch (IllegalAccessException ex) {
           java.util.logging.Logger.getLogger(JframeAuto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       } catch (javax.swing.UnsupportedLookAndFeelException ex) {
           java.util.logging.Logger.getLogger(JframeAuto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
       }
       //</editor-fold>

       /* Create and display the form */
       java.awt.EventQueue.invokeLater(new Runnable() {
           public void run() {
               new JframeAuto().setVisible(true);
           }
       });
   }

   // Variables declaration - do not modify                    
   private javax.swing.JButton btiniciar;
   private javax.swing.JLabel jLabel1;
   private javax.swing.JPanel jPanel1;
   private javax.swing.JLabel jSemaforo;
   private javax.swing.JLabel lbl1;
   private javax.swing.JLabel lbl2;
   private javax.swing.JLabel lbl3;
   private javax.swing.JLabel lbl_barrera;
   // End of variables declaration                  
}





Mod: Obligatorio el uso de etiquetas GeSHi para código.

Ubadelphis

Código Revisado del Condicional para el semáforo
Pero, no toma la 2da. Opción, que es la del color amariillo
for(int i=3; i>0; i--)
   {
     System.out.println(i);
          jSemaforo.setText("Esperar"+i);
      try
        {
        Thread.sleep(3000);
             
              if (i==3)
               {
                  Imagenes = new ImageIcon(getClass().getResource("rojo.jpg")); 
                  jSemaforo.setIcon(Imagenes);
               }
              else if (i==2)
                    {
                     Imagenes = new ImageIcon(getClass().getResource("amarillo.jpg")); 
                     jSemaforo.setIcon(Imagenes);
                     }
           
              else if (i==1)
                    {
                     Imagenes = new ImageIcon(getClass().getResource("verde.jpg")); 
                     jSemaforo.setIcon(Imagenes);
                    } 
        }  catch(InterruptedException e)