Ir ao conteúdo
  • Cadastre-se
Entre para seguir isso  
Diogo Cipriano

Erro ao agendar ytarefa

Recommended Posts

como eu posso evitar esse erro, a forma de fazer usando timertask foi a única que eu encontrei, pare que dê o efeito do botão sendo clicado

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */  
package gênius;

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.Color;
import java.net.URL;
import java.util.Random;
import java.util.TimerTask;
import java.util.Timer;
import javax.swing.JOptionPane;

/**
 *
 * @author acer
 */


public class tela extends javax.swing.JFrame {
    //nome do jogador e pontos

    int pontos = 0;
    String usuario = "";
    
    String njogador = ""; 
    boolean continuar = true;
    //varieaveis de jogadas
    String jjogador = "";
    String maquina = "";
    int aux = 0;

    Random numeroale = new Random();

    /**
     * Creates new form tela
     */
    public tela() {
        initComponents();
    }

    /**
     * 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() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("jogo");
        setAutoRequestFocus(false);

        jButton1.setBackground(new java.awt.Color(0, 0, 255));
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setBackground(new java.awt.Color(255, 0, 0));
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton3.setBackground(new java.awt.Color(0, 204, 0));
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jButton4.setBackground(new java.awt.Color(255, 255, 0));
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });

        jButton5.setText("iniciar jogo");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });

        jButton6.setText("jButton6");

        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(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jButton6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
                            .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 98, Short.MAX_VALUE))
                        .addGap(105, 105, 105))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(152, 152, 152))))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(55, 55, 55))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton5, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(32, 32, 32)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 78, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addComponent(jButton6)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButton3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, 80, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 22, Short.MAX_VALUE)
                .addGap(20, 20, 20))
        );

        pack();
    }// </editor-fold>                        
 Timer tempo1 = new Timer();
    TimerTask tarefa1 = new TimerTask() {
        @Override
        public void run() {
            jButton1.setBackground(Color.white);
            jButton6.setBackground(Color.blue);
            play("b1");
        }
    };
    Timer tempo2 = new Timer();
    TimerTask tarefa2 = new TimerTask() {
        @Override
        public void run() {
            jButton2.setBackground(Color.white);
            jButton6.setBackground(Color.red);

            play("b2");
        }
    };
    Timer tempo3 = new Timer();
    TimerTask tarefa3 = new TimerTask() {
        @Override
        public void run() {
            jButton3.setBackground(Color.white);
            jButton6.setBackground(Color.green);
            play("b2");
        }
    };
    Timer tempo4 = new Timer();
    TimerTask tarefa4 = new TimerTask() {
        @Override
        public void run() {
            jButton4.setBackground(Color.white);
            jButton6.setBackground(Color.yellow);
            play("b2");
        }
    };
    Timer tempovolta1 = new Timer();
    TimerTask tarefavolta1 = new TimerTask() {
        @Override
        public void run() {
            jButton1.setBackground(Color.BLUE);
        }
    };
    Timer tempovolta2 = new Timer();
    TimerTask tarefavolta2 = new TimerTask() {
        @Override
        public void run() {
            jButton2.setBackground(Color.red);
        }
    };
    Timer tempovolta3 = new Timer();
    TimerTask tarefavolta3 = new TimerTask() {
        @Override
        public void run() {
            jButton3.setBackground(Color.green);
        }
    };
    Timer tempovolta4 = new Timer();
    TimerTask tarefavolta4 = new TimerTask() {
        @Override
        public void run() {
            jButton4.setBackground(Color.yellow);
        }
    };

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {                                         

        jLabel1.setText("vez da maquina");
        jLabel1.setForeground(Color.red);

        maquina += numeroale.nextInt(4);
        maquina += numeroale.nextInt(2);
        maquina += numeroale.nextInt(4);

        System.out.println(maquina + "\n" + maquina.length() + "\n" + maquina.substring(0, 1) + "\n" + maquina.substring(1, 2));
        //vez da mqauina
        do {

            for (int i = 0; i < maquina.length(); i++) {
                aux++;
                if ((maquina.substring(i, i + 1)).equals("0")) {
                    System.out.println("1 pressed");
                    tempo1.schedule(tarefa1, 2000 * (i + 1));
                    tempovolta1.schedule(tarefavolta1, 1700 * (i + 2));
                } else if ((maquina.substring(i, i + 1)).equals("1")) {
                    System.out.println("2 pressed");
                    tempo2.schedule(tarefa2, 2000 * (i + 1));
                    tempovolta2.schedule(tarefavolta2, 1700 * (i + 2));
                } else if ((maquina.substring(i, i + 1)).equals("2")) {
                    System.out.println("3 pressed");
                    tempo3.schedule(tarefa3, 2000 * (i + 1));
                    tempovolta3.schedule(tarefavolta3, 1700 * (i + 2));
                } else {
                    System.out.println("4 pressed");
                    tempo4.schedule(tarefa4, 2000 * (i + 1));
                    tempovolta4.schedule(tarefavolta4, 1700 * (i + 2));
                }

            }
            while (maquina.length() == jjogador.length()) {

                for (int i = 0; i < maquina.length(); i++) {
                    if (jjogador.substring(i, i + 1).equals(maquina.substring(i, i + 1))) {
                        pontos += 1;
                    } else {
                        continuar = false;
                    }
                }
                jLabel1.setText("sua vez");
                jLabel1.setForeground(Color.blue);
            }

            //vez do jogador 
        } while (continuar == true); //encerra o jogo
        JOptionPane.showMessageDialog(null, njogador+" você fez "+pontos+"pontos");
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        play("b1");
        jjogador += 1;
        System.out.print("\n" + jjogador);
    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        play("b2");

        System.out.print("\n" + jjogador);

        jjogador += 0;    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        play("b3");
        jjogador += 2;
        System.out.print("\n" + jjogador);
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        play("b4");
        jjogador += 3;
        System.out.print("\n" + jjogador);
    }                                        
    //  som no botão 

    public void play(String audio) {
        URL url = getClass().getResource(audio + ".wav");
        AudioClip audioc = Applet.newAudioClip(url);
        audioc.play();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        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(tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}
Editado por dif
Retirar citação

Compartilhar este post


Link para o post
Compartilhar em outros sites

Crie uma conta ou entre para comentar

Você precisar ser um membro para fazer um comentário

Criar uma conta

Crie uma nova conta em nossa comunidade. É fácil!

Crie uma nova conta

Entrar

Já tem uma conta? Faça o login.

Entrar agora
Entre para seguir isso  





Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas publicações sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×