Dúvida: Thread e GUI (Janela congelando)

Boa Noite Galera.

Antes de tudo gostaria de dizer que sou novo no fórum e estou tentando escrever da melhor forma possível. Caso tenha algo fora das regras por favor me avisem.

Minha dúvida se trata de utilização de threads para evitar que a janela da aplicação trave.
Minha GUI possui 2 locais para setar gifs animados, os quais estão armazenados em vetores.
abaixo de cada label onde os gifs são setados, existem botões para carregar a próxima imagem do vetor.

  • Desta forma, ao clicar no botão responsável por carregar a próxima imagem no label superior (interprete_categoria), o evento ocorre normalmente.
  • Ao passar as imagens no label inferior b[/b], tudo ocorre normal.
  • Ao retornar pro label superior ( (interprete_categoria)) para continuar passando as imagens, o botão trava e não funciona mais.

PS.: Todos os tópicos relacionados a este assunto in dicavam o uso de threads. Tentei usá-las mas não funcionou :cry: .
Obs.: Elimnei agumas partes do código para ficar mais limpo.

Segue abaixo o código:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.ImageIcon;


public class Controle implements ActionListener{
	
	GUI g = new GUI();
	int i=0;
		
	
	public void actionPerformed(final ActionEvent e) {
			
				
		if (e.getSource()==g.b_avancar1){

			//Evento para passar as imagens do label superior

			Runnable run = new Runnable(){  
				public void run(){
				g.interprete_categoria.setIcon(vetor_categorias[i]);				
				String cat = vetor_categorias[i].getDescription().toString();
				cat = cat.substring(19, cat.length()-4);
				g.nome_saudacoes.setText(cat);
					i++;		
				if (i==vetor_categorias.length){
					i=0;
				}
				
				}};   
				Thread t = new Thread(run);  
				t.start();
		}
		
		
		//-----------------------------------------------------------------
		
		
		if (e.getSource()==g.b_avancar2){		
	 
			//Evento para passar as imagens do label superior

			Runnable run = new Runnable(){  
				public void run(){
					
			if (g.nome_saudacoes.getText().equals("saudacoes"))
			{
				g.interprete_palavras.setIcon(vetor_de_palavras[i]);
				String palavra = vetor_de_palavras[i].getDescription().toString();
				palavra = palavra.substring(30, palavra.length()-4);
				g.palavra.setText(palavra);
				i++;
			
				if (i==vetor_de_palavras.length){
				i=0;
				}
			}
			
			if (g.nome_saudacoes.getText().equals("familia"))
			{
				g.interprete_palavras.setIcon(vetor_de_palavras2[i]);
			
				String palavra = vetor_de_palavras2[i].getDescription().toString();
				palavra = palavra.substring(28, palavra.length()-4);
				g.palavra.setText(palavra);
			
				i++;
			
				if (i==vetor_de_palavras2.length){
				i=0;
				}
			}
			
			if (g.nome_saudacoes.getText().equals("identificacao"))
			{
				g.interprete_palavras.setIcon(vetor_de_palavras3[i]);
			
				String palavra = vetor_de_palavras3[i].getDescription().toString();
				palavra = palavra.substring(35, palavra.length()-4);
				g.palavra.setText(palavra);
			
				i++;
			
				if (i==vetor_de_palavras3.length){
				i=0;
				}
			} 

			}};   
			Thread t = new Thread(run);  
			t.start();
		}
		
		
		if (e.getSource()==g.b_add){			
			g.painel_texto.setText(g.painel_texto.getText()+" "+g.palavra.getText());
		}
		
	}	   

}

A princípio não vejo nada de errado, a não ser algumas variáveis que não foram declaradas na classe Controle.

Provavelmente o problema está na classe GUI.

Vanut ,

Vc deve usar Thread mas de outra forma e se tratando de GUI são outras thread´s .
Dê uma olhada aki que vai te ajudar:

http://rfiume.blogspot.com.br/2007/06/o-bsico-sobre-swingworker.html
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/index.html

Tbm já tinha tentado usar o swingworker, mas tbm não deu certo. Acho que utilizei de forma errada. Vou reler os links que você passou e tentar novamente.

Ao usar as threads da forma como está no código acima, o seguinte erro apareceu:

[color=darkred]Exception in thread “Thread-8” java.lang.ArrayIndexOutOfBoundsException: 6
at Controle$1.run(Controle.java:126)
at java.lang.Thread.run(Unknown Source)
[/color]

E o que tem nessa linha?

A parte que carrega o vetor com os Gifs:

“g.interprete_categoria.setIcon(vetor_categorias[i]);”

Já coloquei a Thread nos dois eventos. Somente em um. Mas o erro é sempre esse.

Usando o SwingWork como sugerido pelo Luiz Renato:

[code]if (e.getSource()==g.b_avancar1){

		SwingWorker aWorker = new SwingWorker()   
		{ 
		
		protected Object doInBackground() throws Exception {
			g.interprete_categoria.setIcon(vetor_categorias[i]);				
			String cat = vetor_categorias[i].getDescription().toString();
			cat = cat.substring(19, cat.length()-4);
			g.nome_saudacoes.setText(cat);
				i++;		
			if (i==vetor_categorias.length){
				i=0;
			}
			return null;
		}  
		};  
		aWorker.start();  
	} [/code]

Não consigo nem ao menos rodar o código, pois “[color=red]aWorker.start();[/color]” mantém um erro: "() Add cast to ‘aWorker’ ", ou seja, continuo na mesma. :frowning:

E não funcionar meesmo.
Vc tem que usar o execute() ao invés de start() …

Coloquei o “execute()”, porém não funcionou. O primeiro painel aonde estão os gifs que representam as categorias continua congelado. Apenas o segundo vetor de gifs que passa.

Ah, dessa vez não deu erro nenhum, NENHUM. Apenas não funciona.

Deixa ver como ficou o seu código.

O código completo da Classe Controle. A GUI foi feita utilizando um plugin do Eclipse, o JForm Design.


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.ImageIcon;
import javax.swing.SwingWorker;


public class Controle implements ActionListener{
	
	GUI g = new GUI();
	int i=0;
	
	ImageIcon cat1 = new ImageIcon("Imagens/Categorias/saudacoes.gif");
	ImageIcon cat2 = new ImageIcon("Imagens/Categorias/familia.gif");
	ImageIcon cat3 = new ImageIcon("Imagens/Categorias/identificacao.gif");
	
	ImageIcon vetor_categorias [] = {cat1, cat2, cat3};
	
	ImageIcon esq = new ImageIcon("Imagens/Menu/esq.png");
	ImageIcon cen = new ImageIcon("Imagens/Menu/centralizado.png");
	ImageIcon dir = new ImageIcon("Imagens/Menu/dir.png");
	
	ImageIcon img0 = new ImageIcon("Imagens/Palavras/Saudacoes/2. bem vindo.gif");
	ImageIcon img1 = new ImageIcon("Imagens/Palavras/Saudacoes/3. bom dia.gif");
	ImageIcon img2 = new ImageIcon("Imagens/Palavras/Saudacoes/4. boa tarde.gif");
	ImageIcon img3 = new ImageIcon("Imagens/Palavras/Saudacoes/5. boa noite 1.gif");
	ImageIcon img4 = new ImageIcon("Imagens/Palavras/Saudacoes/6. boa noite 2.gif");
	ImageIcon img5 = new ImageIcon("Imagens/Palavras/Saudacoes/7. com licença.gif");
	ImageIcon img6 = new ImageIcon("Imagens/Palavras/Saudacoes/8. desculpe.gif");
	ImageIcon img7 = new ImageIcon("Imagens/Palavras/Saudacoes/9. perdão.gif");
	ImageIcon img8 = new ImageIcon("Imagens/Palavras/Saudacoes/10. obrigado.gif");
	ImageIcon img9 = new ImageIcon("Imagens/Palavras/Saudacoes/11. de nada.gif");
	
	ImageIcon img10 = new ImageIcon("Imagens/Palavras/Familia/01. marido.gif");
	ImageIcon img11 = new ImageIcon("Imagens/Palavras/Familia/02. esposa.gif");
	ImageIcon img12 = new ImageIcon("Imagens/Palavras/Familia/03. pai.gif");
	ImageIcon img13 = new ImageIcon("Imagens/Palavras/Familia/04. mãe.gif");
	ImageIcon img14 = new ImageIcon("Imagens/Palavras/Familia/05. bebê.gif");
	ImageIcon img15 = new ImageIcon("Imagens/Palavras/Familia/06. filho.gif");
	ImageIcon img16 = new ImageIcon("Imagens/Palavras/Familia/07. filha.gif");
	ImageIcon img17 = new ImageIcon("Imagens/Palavras/Familia/08. menino.gif");
	ImageIcon img18 = new ImageIcon("Imagens/Palavras/Familia/09. menina.gif");
	ImageIcon img19 = new ImageIcon("Imagens/Palavras/Familia/10. jovem.gif");
	ImageIcon img20 = new ImageIcon("Imagens/Palavras/Familia/11. rapaz.gif");
	ImageIcon img21 = new ImageIcon("Imagens/Palavras/Familia/12. moça.gif");
	ImageIcon img22 = new ImageIcon("Imagens/Palavras/Familia/13. irmão.gif");
	ImageIcon img23 = new ImageIcon("Imagens/Palavras/Familia/14. irmã.gif");
	ImageIcon img24 = new ImageIcon("Imagens/Palavras/Familia/15. filho adotivo.gif");
	ImageIcon img25 = new ImageIcon("Imagens/Palavras/Familia/16. meio irmão.gif");
	ImageIcon img26 = new ImageIcon("Imagens/Palavras/Familia/17. vovô.gif");
	ImageIcon img27 = new ImageIcon("Imagens/Palavras/Familia/18. vovó.gif");
	ImageIcon img28 = new ImageIcon("Imagens/Palavras/Familia/19. padrasto.gif");
	ImageIcon img29 = new ImageIcon("Imagens/Palavras/Familia/20. madrasta.gif");
	ImageIcon img30 = new ImageIcon("Imagens/Palavras/Familia/21. tio.gif");
	ImageIcon img31 = new ImageIcon("Imagens/Palavras/Familia/22. tia.gif");
	ImageIcon img32 = new ImageIcon("Imagens/Palavras/Familia/23. primo.gif");
	ImageIcon img33 = new ImageIcon("Imagens/Palavras/Familia/24. sogra.gif");
	ImageIcon img34 = new ImageIcon("Imagens/Palavras/Familia/25. cunhado.gif");
	ImageIcon img35 = new ImageIcon("Imagens/Palavras/Familia/26. cunhada.gif");
	ImageIcon img36 = new ImageIcon("Imagens/Palavras/Familia/27. sobrinho.gif");
	ImageIcon img37 = new ImageIcon("Imagens/Palavras/Familia/28. madrinha.gif");
	ImageIcon img38 = new ImageIcon("Imagens/Palavras/Familia/29. namoradpa.gif");
	ImageIcon img39 = new ImageIcon("Imagens/Palavras/Familia/30. enteado.gif");
	ImageIcon img40 = new ImageIcon("Imagens/Palavras/Familia/31. parentes.gif");
	ImageIcon img41 = new ImageIcon("Imagens/Palavras/Familia/32. gêmeos.gif");
	ImageIcon img42 = new ImageIcon("Imagens/Palavras/Familia/33. amigo.gif");
	ImageIcon img43 = new ImageIcon("Imagens/Palavras/Familia/34. bisavó.gif");
	ImageIcon img44 = new ImageIcon("Imagens/Palavras/Familia/35. bisavô.gif");
	
	ImageIcon img45 = new ImageIcon("Imagens/Palavras/Identificacao/01. nome.gif");
	ImageIcon img46 = new ImageIcon("Imagens/Palavras/Identificacao/02. sinal.gif");
	ImageIcon img47 = new ImageIcon("Imagens/Palavras/Identificacao/03. idade.gif");
	ImageIcon img48 = new ImageIcon("Imagens/Palavras/Identificacao/04. eu.gif");
	ImageIcon img49 = new ImageIcon("Imagens/Palavras/Identificacao/05. voce.gif");
	ImageIcon img50 = new ImageIcon("Imagens/Palavras/Identificacao/06. ele ou ela.gif");
	ImageIcon img51 = new ImageIcon("Imagens/Palavras/Identificacao/07. nos.gif");
	ImageIcon img52 = new ImageIcon("Imagens/Palavras/Identificacao/08. seu ou sua.gif");
	ImageIcon img53 = new ImageIcon("Imagens/Palavras/Identificacao/09. meu ou minha.gif");
	ImageIcon img54 = new ImageIcon("Imagens/Palavras/Identificacao/10. homem.gif");
	ImageIcon img55 = new ImageIcon("Imagens/Palavras/Identificacao/11. solteiro.gif");
	ImageIcon img56 = new ImageIcon("Imagens/Palavras/Identificacao/12. noivo.gif");
	ImageIcon img57 = new ImageIcon("Imagens/Palavras/Identificacao/13. viúvo.gif");
	ImageIcon img58 = new ImageIcon("Imagens/Palavras/Identificacao/14. separado.gif");
	ImageIcon img59 = new ImageIcon("Imagens/Palavras/Identificacao/15. casado.gif");
	ImageIcon img60 = new ImageIcon("Imagens/Palavras/Identificacao/16. adulto.gif");
	
	
	ImageIcon vetor_de_palavras [] = {img0, img1, img2, img3, img4, img5, img6, img7, img8, img9};
	ImageIcon vetor_de_palavras2 [] = {img10, img11, img12, img13, img14, img15, img16, img17, img18, img19, img20, img21, img22, img23, img24, img25, img26};
	ImageIcon vetor_de_palavras3 [] = {img45, img46, img47, img48, img49, img50, img51, img52, img53, img54, img55, img56, img57, img58, img59, img60};
	
	public Controle(){	
		
		g.b_esq.setIcon(esq);
		g.b_cen.setIcon(cen);
		g.b_dir.setIcon(dir);
		
		g.setVisible(true);
		
		g.b_retro1.addActionListener(this);
		g.b_retro2.addActionListener(this);
		g.b_avancar1.addActionListener(this);
		g.b_avancar2.addActionListener(this);
		g.b_add.addActionListener(this);		
	}
	
			
	public void actionPerformed(final ActionEvent e) {
			
		
		if (e.getSource()==g.b_avancar1){
			
			SwingWorker aWorker = new SwingWorker() { 
			
			protected Object doInBackground() throws Exception {
				g.interprete_categoria.setIcon(vetor_categorias[i]);				
				String cat = vetor_categorias[i].getDescription().toString();
				cat = cat.substring(19, cat.length()-4);
				g.nome_saudacoes.setText(cat);
					i++;		
				if (i==vetor_categorias.length){
					i=0;
				}
				return null;
			}  
			};  
			aWorker.execute();  
		}
		
		
		//-----------------------------------------------------------------
		
		
		if (e.getSource()==g.b_avancar2){			 
			
			//Runnable run = new Runnable(){  
				//public void run(){
			if (g.nome_saudacoes.getText().equals("saudacoes"))
			{
				g.interprete_palavras.setIcon(vetor_de_palavras[i]);
				String palavra = vetor_de_palavras[i].getDescription().toString();
				palavra = palavra.substring(30, palavra.length()-4);
				g.palavra.setText(palavra);
				i++;
			
				if (i==vetor_de_palavras.length){
				i=0;
				}
			}
			
			if (g.nome_saudacoes.getText().equals("familia"))
			{
				g.interprete_palavras.setIcon(vetor_de_palavras2[i]);
			
				String palavra = vetor_de_palavras2[i].getDescription().toString();
				palavra = palavra.substring(28, palavra.length()-4);
				g.palavra.setText(palavra);
			
				i++;
			
				if (i==vetor_de_palavras2.length){
				i=0;
				}
			}
			
			if (g.nome_saudacoes.getText().equals("identificacao"))
			{
				g.interprete_palavras.setIcon(vetor_de_palavras3[i]);
			
				String palavra = vetor_de_palavras3[i].getDescription().toString();
				palavra = palavra.substring(35, palavra.length()-4);
				g.palavra.setText(palavra);
			
				i++;
			
				if (i==vetor_de_palavras3.length){
				i=0;
				}
			}
			/*}};   
			Thread t = new Thread(run);  
			t.start();*/
		}
		
		if (e.getSource()==g.b_add){			
			g.painel_texto.setText(g.painel_texto.getText()+" "+g.palavra.getText());
		}
		
	}
		   

}