Thread

Galera to fazendo um quiz simples. queria q quando o jogador clica-se EX: no botão A a imagem emiticom mudasse imediatamente e so apos alguns segundos mudasse a imagem q tem a pergunta para proxima pergunta e o emoticon volta-se ao q tava antes, tentei usar Thread mas sou meio burrinho, ate consegui da um slemp mas quando aperto no A apoz um tempo muda tudo junto e não como queria.
public class Tela_Game extends javax.swing.JFrame {

    public int pontos = 0;
    public int contador = 1;

    public Tela_Game() {

        if (pontos / 2 < pontos) {
            j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/espera.gif")));
        }

        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        btn_A = new javax.swing.JButton();
        btn_B = new javax.swing.JButton();
        btn_C = new javax.swing.JButton();
        btn_D = new javax.swing.JButton();
        jL_Pontos = new javax.swing.JLabel();
        j_Emotion = new javax.swing.JLabel();
        j_progreço = new javax.swing.JProgressBar();
        jL_BKperguntas = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setMinimumSize(new java.awt.Dimension(800, 575));
        setPreferredSize(new java.awt.Dimension(800, 575));
        getContentPane().setLayout(null);

        jPanel1.setAutoscrolls(true);
        jPanel1.setOpaque(false);
        jPanel1.setLayout(new java.awt.GridLayout(1, 0, 20, 0));

        btn_A.setFont(new java.awt.Font("Swis721 Hv BT", 0, 36)); // NOI18N
        btn_A.setText("A");
        btn_A.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_AActionPerformed(evt);
            }
        });
        jPanel1.add(btn_A);

        btn_B.setFont(new java.awt.Font("Swis721 Hv BT", 0, 36)); // NOI18N
        btn_B.setText("B");
        btn_B.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_BActionPerformed(evt);
            }
        });
        jPanel1.add(btn_B);

        btn_C.setFont(new java.awt.Font("Swis721 Hv BT", 0, 36)); // NOI18N
        btn_C.setText("C");
        btn_C.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_CActionPerformed(evt);
            }
        });
        jPanel1.add(btn_C);

        btn_D.setFont(new java.awt.Font("Swis721 Hv BT", 0, 36)); // NOI18N
        btn_D.setText("D");
        btn_D.setInheritsPopupMenu(true);
        btn_D.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_DActionPerformed(evt);
            }
        });
        jPanel1.add(btn_D);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(10, 430, 430, 70);

        jL_Pontos.setFont(new java.awt.Font("Tahoma", 0, 48)); // NOI18N
        jL_Pontos.setForeground(new java.awt.Color(51, 255, 0));
        jL_Pontos.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jL_Pontos.setText("0000");
        getContentPane().add(jL_Pontos);
        jL_Pontos.setBounds(540, 200, 120, 40);

        j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/espera.gif"))); // NOI18N
        getContentPane().add(j_Emotion);
        j_Emotion.setBounds(580, 340, 150, 150);
        getContentPane().add(j_progreço);
        j_progreço.setBounds(20, 505, 740, 20);

        jL_BKperguntas.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
        jL_BKperguntas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/perguntas/f1_p1.jpg"))); // NOI18N
        jL_BKperguntas.setVerticalAlignment(javax.swing.SwingConstants.TOP);
        getContentPane().add(jL_BKperguntas);
        jL_BKperguntas.setBounds(0, 0, 800, 530);

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

    Codigos codigos = new Codigos();


    private void btn_AActionPerformed(java.awt.event.ActionEvent evt) {                                      
 // pergunta _ 1 ----------------------------------------
        if (contador == 1) {
            // PARA TESTAR SO USEU O RUN AQUI NA RIMEIRA PERGUNTA
            
            j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/espera.gif")));
             codigos.run();
             j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/emotion_1.gif")));
            contador += 1;

            jL_BKperguntas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/perguntas/f1_p2.jpg")));
            System.out.println("Você errou! contador= " + contador);
        } // pergunta _ 2 ----------------------------------------
        else if (contador == 2) {

            contador += 1;
            pontos += 5;
            jL_Pontos.setText(Integer.toString(pontos));
            jL_BKperguntas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/perguntas/f1_p3.jpg")));

            System.out.println("Você acertou! contador= " + contador);
        } // pergunta _ 3 ----------------------------------------
        else if (contador == 3) {

            contador += 1;
            jL_BKperguntas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/perguntas/f1_p4.jpg")));
            System.out.println("Você errou! contador= " + contador);
        } // pergunta _ 4 ----------------------------------------
        else if (contador == 4) {

            contador += 1;
            pontos += 5;
            jL_BKperguntas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/perguntas/f1_p5.jpg")));
            System.out.println("Você acertou! contador= " + contador);
        } // pergunta _ 5 ----------------------------------------
        else if (contador == 5) {

            contador += 1;
            pontos -= 8;
            jL_BKperguntas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/perguntas/f1_p5.jpg")));
            System.out.println("Você errou! contador= " + contador);
        }


    }                                     

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

    }                                     

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

    }                                     

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

    }                                     

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tela_Login().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton btn_A;
    private javax.swing.JButton btn_B;
    private javax.swing.JButton btn_C;
    private javax.swing.JButton btn_D;
    private javax.swing.JLabel jL_BKperguntas;
    private javax.swing.JLabel jL_Pontos;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JLabel j_Emotion;
    private javax.swing.JProgressBar j_progreço;
    // End of variables declaration                   

   

}

public class Codigos extends Thread {

    public void respostas() {

    }

    @Override
    public void run() {

        for (int i = 0; i < 5; i++) {
            System.out.println("Temporizador: " + i);

            try {
                Thread.sleep(600);
            } catch (InterruptedException ex) {

            }
        }

    }

}

Ao usar threads, vc não pode chamar o método run diretamente. Para rodar a thread, vc tem que chamar o método start. E como a thread é executada em paralelo, quando vc iniciar sua execução, não irá ocorrer um tempo de espera até que as imagens sejam trocadas, como vc quer.

hum vou tentar aqui acho q entendi

Veja:

metodoA();			// processa alguma lógica
threadA.start();	// faz o sistema aguardar um tempo
metodoB();			// processa outra lógica

Ao executar esse código:

  • o metodoA será executado primeiro;
  • a threadA será iniciada para fazer o sistema aguardar algum tempo
  • o metodoB será executado imediatamente (sem esperar pela execução da thread)

Repare que o metodoB será executado imediatamente, pois a threadA executa em paralelo com a thread principal do seu programa, pois as thread são feitas para isso. Há formas de controlar a concorrência fazendo uma thread esperar outra terminar, mas isso exige um pouco mais de leitura para entender melhor o funcionamento.

Referências:
wait and notify() Methods in Java
The Thread.join() Method in Java

nossa agora me explicou a teoria das cordas de uma forma que eu entendi assim como 1 +1 e 2, e eu me batendo com essas threads. vlw obrigado.

Sobre o que vc quer fazer, tente isso e veja como fica o comportamento:

j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/espera.gif")));
codigos.start();
codigos.join();
j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/emotion_1.gif")));

Deixa o sleep na thread

pera

Gerou erro:

private void btn_AActionPerformed(java.awt.event.ActionEvent evt) {                                      
	// pergunta _ 1 ----------------------------------------
	
	if (contador == 1) {
		// PARA TESTAR SO USEU O RUN AQUI NA RIMEIRA PERGUNTA
		j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/espera.gif")));
		thread.start();
		
		try {
			thread.join();
		} catch (InterruptedException ex) {
		}
		
		j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/emotion_1.gif")));
==========ERRO==============
Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
	at sun.awt.Win32GraphicsConfig.getBounds(Native Method)
	at sun.awt.Win32GraphicsConfig.getBounds(Win32GraphicsConfig.java:222)
	at java.awt.Window.init(Window.java:505)
	at java.awt.Window.<init>(Window.java:537)
	at java.awt.Frame.<init>(Frame.java:420)
	at java.awt.Frame.<init>(Frame.java:385)
	at javax.swing.JFrame.<init>(JFrame.java:189)
	at Tela_Game.<init>(Tela_Game.java:11)
	at Codigos.<init>(Codigos.java:5)
	at Tela_Game.<init>(Tela_Game.java:106)
	at Codigos.<init>(Codigos.java:5)
	at Tela_Game.<init>(Tela_Game.java:106)
	at Codigos.<init>(Codigos.java:5)
	at Tela_Game.<init>(Tela_Game.java:106)
	at Codigos.<init>(Codigos.java:5)
	at Tela_Game.<init>(Tela_Game.java:106)
	at Codigos.<init>(Codigos.java:5)
	at Tela_Game.<init>(Tela_Game.java:106)
	at Codigos.<init>(Codigos.java:5)

Essa thread é a classe Codigos?

sim mudei para facilita aqui esqueci de avisar, tb achei q daria certo tem logica …

O que tem nessa linha: Codigos.java:5? (linha 5 da classe Codigos)

tem o " Tela_Game tg = new Tela_Game();"
public class Codigos extends Thread {

Tela_Game tg = new Tela_Game();

public Codigos() {

}


public void metodoA(){
  tg.getJ_Emotion().setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/emotion_1.gif")));
}
public void metodoB(){
    tg.getJ_Emotion().setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/espera.gif")));
}



@Override
public void run() {

    for (int i = 0; i < 5; i++) {
        System.out.println("Temporizador: " + i);

        try {
            Thread.sleep(600);
        } catch (InterruptedException ex) {

        }
    }

Remove essa linha. Nâo precisa criar a Tela_Game dentro de Codigos. Por isso deu erro, pois a Tela_Game cria Codigos, que cria Tela_Game que cria Codigos, etc. Isso fica num loop infinito.

Deixe o código como estava (igual o código da sua pergunta) e apenas mude o que coloquei antes:

j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/espera.gif")));
codigos.start();
codigos.join();
j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/emotion_1.gif")));

memovi mas agora troca todas as imagens juntas.

public class Codigos extends Thread {

public Codigos() {

}

@Override
public void run() {

    for (int i = 0; i < 5; i++) {
        System.out.println("Temporizador: " + i);

        try {
            Thread.sleep(600);
        } catch (InterruptedException ex) {

        }
    }

}

}

tem como te enviar por 4sherad para vc olhar o ae?

pode sim

Obrigado.

Usar o join como disse não resolve, pois o join pausa a thread principal até que a outra thread termine, com isso, o label não será atualizado (pois a thread está descansando). Vendo isso, usei a seguinte solução:

Criei uma interface que dará a capacidade ao frame de alterar o ícone do label:

public interface IconNotifier {
    void change(String path);
}

Fiz o jFrame implementar essa interface:

public class Tela_Game extends javax.swing.JFrame implements IconNotifier {
    // todo o código do frame

    @Override
    public void change(String path) {
        j_Emotion.setIcon(new javax.swing.ImageIcon(getClass().getResource(path)));
    }
}

O método change que irá atualizar o label agora. E ele será chamado pela thread Codigos.

A classe Codigos ficou assim:

public class Codigos extends Thread {
	
	private final IconNotifier iconNotifier;
	private final String before;
	private final String after;
	
	public Codigos(IconNotifier iconNotifier, String before, String after) {
		this.iconNotifier = iconNotifier;
		this.before = before;
		this.after = after;
	}

	@Override
	public void run() {
		iconNotifier.change(before);
		
		try {
			for (int i = 0; i < 5; i++) {
				System.out.println("Temporizador: " + i);
				Thread.sleep(500);
			}
		} catch (InterruptedException ex) {}
		
		iconNotifier.change(after);
	}
}

E a ação do botão ficou assim:

private void btn_AActionPerformed(java.awt.event.ActionEvent evt) {
    Codigos thread = new Codigos(this, "/res/emotion_1.gif", "/res/espera.gif");

    if (contador == 1) {
        thread.start();
        contador += 1;
        jL_BKperguntas.setIcon(new javax.swing.ImageIcon(getClass().getResource("/res/perguntas/f1_p2.jpg")));
        System.out.println("Você errou! contador= " + contador);
    }

    // daí vem o resto do código

obrigado brother bela ajuda vou poder usar nas aulas de informatica brigadão mesmo.se Deus quiser esse ano faço ciências da computação.

Funcionou da forma como queria?