elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Usando Git para manipular el directorio de trabajo, el índice y commits (segunda parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  Java
| | | |-+  Ciclo de Semáforo
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: Ciclo de Semáforo  (Leído 3,494 veces)
Ubadelphis

Desconectado Desconectado

Mensajes: 3


Ver Perfil
Ciclo de Semáforo
« en: 20 Octubre 2020, 02:58 am »


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
  1. for(int i=3; i>0; i--)
  2. {
  3.  System.out.println(i);
  4.         // jSemaforo.setText("Esperar"+i);
  5.   try
  6.     {                                                  
  7.      Thread.sleep(3000);
  8.  
  9.              if (i==3)
  10.               {
  11.                  Imagenes = new ImageIcon(getClass().getResource("rojo.jpg"));  
  12.                  jSemaforo.setIcon(Imagenes);
  13.                  jSemaforo.setText("Esperar"+i);
  14.               }
  15.              else
  16.              {
  17.                  if (i==2)
  18.                     {
  19.                      Imagenes = new ImageIcon(getClass().getResource("amarillo.jpg"));  
  20.                       jSemaforo.setIcon(Imagenes);
  21.                       jSemaforo.setText("Preparados"+i);
  22.                      }
  23.                    else
  24. {
  25.         if (i==3)
  26.                        {
  27.                         Imagenes = new ImageIcon(getClass().getResource("verde.jpg"));  
  28.                         jSemaforo.setIcon(Imagenes);
  29.                         jSemaforo.setText("Partidas"+i);
  30.                        }
  31.  }
  32.  }  
  33.  
  34.     }  catch(InterruptedException e){}



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


« Última modificación: 24 Octubre 2020, 19:44 pm por #!drvy » En línea

rub'n


Desconectado Desconectado

Mensajes: 1.217


(e -> λ("live now")); tatuar -> λ("α");


Ver Perfil WWW
Re: Ciclo de Semáforo
« Respuesta #1 en: 20 Octubre 2020, 16:11 pm »

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


En línea



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 ki
Ubadelphis

Desconectado Desconectado

Mensajes: 3


Ver Perfil
Re: Ciclo de Semáforo
« Respuesta #2 en: 24 Octubre 2020, 19:36 pm »

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

Código
  1. import javax.swing.JLabel;
  2. import javax.swing.JOptionPane;
  3. import javax.swing.Icon;
  4. import javax.swing.ImageIcon;
  5. import java.util.Timer;
  6. import java.util.TimerTask;
  7. import java.util.logging.Level;
  8. import java.util.logging.Logger;
  9.  
  10.  
  11.  
  12. /**
  13.  *
  14.  * @author conej
  15.  */
  16. public class JframeAuto extends javax.swing.JFrame {
  17.    public enum ColorSemaforo {
  18. Rojo, Ambar, Verde;
  19. }
  20.  
  21.  
  22.    /**
  23.      * Creates new form JframeAuto
  24.      */
  25.    public JframeAuto() {
  26.        initComponents();
  27.    }
  28.    public JLabel getlbl1(){
  29.        return lbl1;
  30.    }
  31.    public JLabel getlbl2(){
  32.        return lbl2;
  33.    }
  34.    public JLabel getlbl3(){
  35.        return lbl3;
  36.    }
  37.    public JLabel getlbl_barrera(){
  38.        return lbl_barrera;
  39.    }
  40.  
  41.    /**
  42.      * This method is called from within the constructor to initialize the form.
  43.      * WARNING: Do NOT modify this code. The content of this method is always
  44.      * regenerated by the Form Editor.
  45.      */
  46.    @SuppressWarnings("unchecked")
  47.    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
  48.    private void initComponents() {
  49.  
  50.        jPanel1 = new javax.swing.JPanel();
  51.        lbl1 = new javax.swing.JLabel();
  52.        lbl2 = new javax.swing.JLabel();
  53.        lbl_barrera = new javax.swing.JLabel();
  54.        lbl3 = new javax.swing.JLabel();
  55.        jSemaforo = new javax.swing.JLabel();
  56.        jLabel1 = new javax.swing.JLabel();
  57.        btiniciar = new javax.swing.JButton();
  58.  
  59.        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
  60.  
  61.        jPanel1.setBackground(new java.awt.Color(102, 255, 102));
  62.        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
  63.  
  64.        lbl1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
  65.        lbl1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/carreraautos/Corredor_Azul.jpg"))); // NOI18N
  66.        lbl1.setText("1");
  67.  
  68.        lbl2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
  69.        lbl2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/carreraautos/Corredor_Naranja.jpg"))); // NOI18N
  70.        lbl2.setText("2");
  71.        lbl2.setName(""); // NOI18N
  72.  
  73.        lbl_barrera.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 0, 51), 10));
  74.  
  75.        lbl3.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
  76.        lbl3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/carreraautos/Corredor_Negro.jpg"))); // NOI18N
  77.        lbl3.setText("3");
  78.  
  79.        jSemaforo.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
  80.        jSemaforo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/carreraautos/rojo.jpg"))); // NOI18N
  81.        jSemaforo.setText("Partida");
  82.  
  83.        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
  84.        jPanel1.setLayout(jPanel1Layout);
  85.        jPanel1Layout.setHorizontalGroup(
  86.            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  87.            .addGroup(jPanel1Layout.createSequentialGroup()
  88.                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  89.                    .addGroup(jPanel1Layout.createSequentialGroup()
  90.                        .addContainerGap()
  91.                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
  92.                            .addComponent(lbl2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  93.                            .addComponent(lbl3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  94.                            .addComponent(lbl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
  95.                    .addGroup(jPanel1Layout.createSequentialGroup()
  96.                        .addGap(20, 20, 20)
  97.                        .addComponent(jSemaforo)))
  98.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  99.                .addComponent(lbl_barrera)
  100.                .addContainerGap())
  101.        );
  102.        jPanel1Layout.setVerticalGroup(
  103.            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  104.            .addGroup(jPanel1Layout.createSequentialGroup()
  105.                .addGap(18, 18, 18)
  106.                .addComponent(lbl1)
  107.                .addGap(39, 39, 39)
  108.                .addComponent(lbl2)
  109.                .addGap(26, 26, 26)
  110.                .addComponent(lbl3, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
  111.                .addGap(66, 66, 66)
  112.                .addComponent(jSemaforo)
  113.                .addContainerGap(59, Short.MAX_VALUE))
  114.            .addComponent(lbl_barrera, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  115.        );
  116.  
  117.        jLabel1.setText("Carrera de Autos");
  118.  
  119.        btiniciar.setText("Iniciar Carrera");
  120.        btiniciar.addActionListener(new java.awt.event.ActionListener() {
  121.            public void actionPerformed(java.awt.event.ActionEvent evt) {
  122.                btiniciarActionPerformed(evt);
  123.            }
  124.        });
  125.  
  126.        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
  127.        getContentPane().setLayout(layout);
  128.        layout.setHorizontalGroup(
  129.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  130.            .addGroup(layout.createSequentialGroup()
  131.                .addContainerGap()
  132.                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  133.                    .addGroup(layout.createSequentialGroup()
  134.                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  135.                        .addContainerGap())
  136.                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  137.                        .addGap(0, 439, Short.MAX_VALUE)
  138.                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 199, javax.swing.GroupLayout.PREFERRED_SIZE)
  139.                        .addGap(97, 97, 97))))
  140.            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
  141.                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  142.                .addComponent(btiniciar, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
  143.                .addGap(273, 273, 273))
  144.        );
  145.        layout.setVerticalGroup(
  146.            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
  147.            .addGroup(layout.createSequentialGroup()
  148.                .addGap(4, 4, 4)
  149.                .addComponent(jLabel1)
  150.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  151.                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
  152.                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
  153.                .addComponent(btiniciar)
  154.                .addGap(36, 36, 36))
  155.        );
  156.  
  157.        pack();
  158.    }// </editor-fold>                        
  159.  
  160.    private void btiniciarActionPerformed(java.awt.event.ActionEvent evt) {                                          
  161.  
  162.        lbl1.setLocation(0,lbl1.getLocation().y);
  163.        lbl2.setLocation(0,lbl2.getLocation().y);
  164.        lbl3.setLocation(0,lbl3.getLocation().y);
  165.        Carrera hilo1=new Carrera(lbl1, this);
  166.        Carrera hilo2=new Carrera(lbl2, this);
  167.        Carrera hilo3=new Carrera(lbl3, this);
  168.  
  169.     long inicio;
  170.      inicio=System.currentTimeMillis()/1000;
  171.      System.out.println("segundo: " + inicio);  
  172.        Icon Imagenes;  
  173.  
  174.        Semaforo misemaforo=new Semaforo();
  175.  
  176.        int c=0;
  177.  
  178.  
  179.      for(int i=3; i>0; i--)
  180.   {
  181.     System.out.println(i);
  182.         // jSemaforo.setText("Esperar"+i);
  183.      try
  184.        {                                                
  185.         Thread.sleep(3000);
  186.  
  187.              if (i==3)
  188.               {
  189.                  Imagenes = new ImageIcon(getClass().getResource("rojo.jpg"));
  190.                  jSemaforo.setIcon(Imagenes);
  191.                  jSemaforo.setText("Esperar"+i);
  192.               }
  193.              else
  194.              {
  195.                  if (i==2)
  196.                     {
  197.                      Imagenes = new ImageIcon(getClass().getResource("amarillo.jpg"));
  198.                       jSemaforo.setIcon(Imagenes);
  199.                       jSemaforo.setText("Preparados"+i);
  200.                      }
  201.                    else
  202.         {
  203.               if (i==3)
  204.                        {
  205.                         Imagenes = new ImageIcon(getClass().getResource("verde.jpg"));
  206.                         jSemaforo.setIcon(Imagenes);
  207.                         jSemaforo.setText("Partidas"+i);
  208.                        }
  209.                 }
  210.           }                
  211.  
  212.        }  catch(InterruptedException e){}
  213.  
  214.           {
  215.            Imagenes = new ImageIcon(getClass().getResource("verde.jpg"));  
  216.            jSemaforo.setIcon(Imagenes);
  217.            }
  218. }
  219.  
  220.  
  221.        hilo1.start();
  222.        hilo2.start();
  223.        hilo3.start();
  224.  
  225.  
  226.  
  227.  
  228.    }                                        
  229.  
  230.  
  231.    public static void main(String args[]) {
  232.  
  233.        try {
  234.            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
  235.                if ("Nimbus".equals(info.getName())) {
  236.                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
  237.                    break;
  238.                }
  239.            }
  240.        } catch (ClassNotFoundException ex) {
  241.            java.util.logging.Logger.getLogger(JframeAuto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  242.        } catch (InstantiationException ex) {
  243.            java.util.logging.Logger.getLogger(JframeAuto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  244.        } catch (IllegalAccessException ex) {
  245.            java.util.logging.Logger.getLogger(JframeAuto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  246.        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
  247.            java.util.logging.Logger.getLogger(JframeAuto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
  248.        }
  249.        //</editor-fold>
  250.  
  251.        /* Create and display the form */
  252.        java.awt.EventQueue.invokeLater(new Runnable() {
  253.            public void run() {
  254.                new JframeAuto().setVisible(true);
  255.            }
  256.        });
  257.    }
  258.  
  259.    // Variables declaration - do not modify                    
  260.    private javax.swing.JButton btiniciar;
  261.    private javax.swing.JLabel jLabel1;
  262.    private javax.swing.JPanel jPanel1;
  263.    private javax.swing.JLabel jSemaforo;
  264.    private javax.swing.JLabel lbl1;
  265.    private javax.swing.JLabel lbl2;
  266.    private javax.swing.JLabel lbl3;
  267.    private javax.swing.JLabel lbl_barrera;
  268.    // End of variables declaration                  
  269. }



Mod: Obligatorio el uso de etiquetas GeSHi para código.
« Última modificación: 24 Octubre 2020, 19:44 pm por #!drvy » En línea

Ubadelphis

Desconectado Desconectado

Mensajes: 3


Ver Perfil
Re: Ciclo de Semáforo
« Respuesta #3 en: 24 Octubre 2020, 20:51 pm »

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)
En línea

Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
semaforo en puerto paralelo en vb
Electrónica
prosk8er 1 4,637 Último mensaje 1 Abril 2005, 10:45 am
por BADBYTE-K
Semáforo con Arduino
Electrónica
@synthesize 2 10,646 Último mensaje 18 Junio 2010, 19:40 pm
por Debci
Cambiar De Semaforo A Tuberias
Programación C/C++
candycrush 0 1,504 Último mensaje 30 Agosto 2014, 02:02 am
por candycrush
Simulacion de semaforo (AYUDA)
Programación Visual Basic
reeyesg 7 7,186 Último mensaje 14 Diciembre 2014, 06:20 am
por agusdmb
Ciclo Do While anidado que no coge al ciclo interior
Programación Visual Basic
Baldomero123 1 6,372 Último mensaje 4 Enero 2018, 14:19 pm
por Baldomero123
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines