Como chamar uma tarefa varias vezes

4 respostas
D
Timer tempovolta1 = new Timer();
TimerTask tarefavolta1 = new TimerTask() {
     @Override
    public void run() {
  jButton1.setBackground(Color.BLUE);
    }
};

uso esse código para chamar a tarefa
tempo1.schedule(tarefa1, 2000 );

porém se eu tentar chamar ela novamente
tempo1.schedule(tarefa1, 8000 );

apareçe o seguinte erro

Exception in thread “AWT-EventQueue-0” java.lang.IllegalStateException:
Task already scheduled or cancelled`

porque estou chamando ela novamente existe algo que possa fazer para chamar a mesma varias vezes ?

4 Respostas

Jonas_B_a_r_r_o_s

Task already scheduled - Tarefa já programada
Parece que você não pode fazer isso. Porque você não coloca o problema da questão, o que você quer fazer

D

`package gênius;

import java.applet.Applet;

import java.applet.AudioClip;

import java.awt.Color;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import java.net.URL;

import java.util.Random;

import java.util.Timer;

import java.util.TimerTask;
import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.SwingConstants;

public class tela {

//nome do jogador e pontos
int pontos = 0 ;
String usuario = "";

//varieaveis de jogadas
String jjogador = "";
String maquina ="";
int aux ;

Random numeroale = new Random();



// janela de exibição
public void janela(){
	JFrame  ftela = new JFrame();
	ftela.setTitle("Gênius");
	ftela.setSize(400, 600);
	ftela.setBackground(Color.white);
	ftela.setLocationRelativeTo(null);
	ftela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	ftela.setVisible(true);
	ftela.setLayout(null);
	
	//boões 
	JButton b1 = new JButton("0");
	b1.setBounds(120, 220, 80, 80);
	b1.setVisible(true);
	b1.setBackground(Color.BLUE);
    
	
	JButton b2 = new JButton("1");
	b2.setBounds(200, 220, 80, 80);
	b2.setVisible(true);
	b2.setBackground(Color.red);
	
	JButton b3 = new JButton("2");
	b3.setBounds(120, 300, 80, 80);
	b3.setVisible(true);
	b3.setBackground(Color.GREEN);

	
	JButton b4 = new JButton("3");
	b4.setBounds(200, 300, 80, 80);
	b4.setVisible(true);
	b4.setBackground(Color.YELLOW);
	
	// exibir pontos
	JLabel mPontos = new JLabel("pontos :"+maquina);
	mPontos.setHorizontalAlignment(SwingConstants.CENTER);
	mPontos.setBounds(70, 150, 80,80);
	
	//botão de inicar o jogo
	JButton inicio = new JButton("INICIAR");
	inicio.setBounds(90, 10, 80, 30);
	inicio.setVisible(true);

	
	JPanel p1 = new JPanel();
	p1.setVisible(true);
	ftela.add(mPontos);
	ftela.add(b1);
	ftela.add(b2);
	ftela.add(b3);
	ftela.add(b4);
	ftela.add(inicio);
	
	
	
	//tempo de pause para efeito de botão clicado
	Timer tempo = new Timer();
	 TimerTask tarefa = new TimerTask() {

		@Override
		public void run() {
			b1.setBackground(Color.BLUE);
		}
	

	 }   ; 
		Timer tempo2 = new Timer();
		 TimerTask tarefa2 = new TimerTask() {

			@Override
			public void run() {
				b2.setBackground(Color.red);
			}
		
	
		 }   ; 
			Timer tempo3 = new Timer();
			 TimerTask tarefa3 = new TimerTask() {

				@Override
				public void run() {
					b3.setBackground(Color.green);
				}
			
		
			 }   ; 
				Timer tempo4 = new Timer();
				 TimerTask tarefa4 = new TimerTask() {

					@Override
					public void run() {
						b4.setBackground(Color.yellow);
					}
				
			
				 }   ; 
				 
				 //fechamento de pausa do botão
				 
				 
				 
	//gerar numeros aleatorios
	
//	maquina += num.nextInt(4);
	
	
	// acão do botão inicio
   inicio.addActionListener(new ActionListener() {
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		maquina += numeroale.nextInt(4);
		maquina += numeroale.nextInt(4);
		System.out.println(maquina+"\n"+maquina.length()+"\n"+maquina.substring(0,1)+"\n"+maquina.substring(1,2));
		//vez da mqauina
	for (int i = 0; i < maquina.length(); i++) {
		 
		System.out.println("valor atual"+maquina.substring(i,1));
	   
		
		
		if((maquina.substring(i,i+1)).equals("0")){
			System.out.println("1 pressed");
			play("b1");
			b1.setBackground(Color.white);
			tempo.scheduleAtFixedRate(tarefa, 1000, 1000);
			
			}
		else if((maquina.substring(i,i+1)).equals("1")){
			System.out.println("2 pressed");
			play("b2");
			b2.setBackground(Color.white);
			tempo2.scheduleAtFixedRate(tarefa2, 1000, 1000);				
			
		}
		else if((maquina.substring(i,i+1)).equals("2")){
			System.out.println("3 pressed");
			play("b3");
			b3.setBackground(Color.white);
			tempo3.scheduleAtFixedRate(tarefa3, 1000, 1000);
			
			
			
			
		
		} else{
			System.out.println("4 pressed");
			play("b4");
			b4.setBackground(Color.white);
			tempo4.scheduleAtFixedRate(tarefa4, 1000, 1000);
			
		
		
		}
	
		
		
		
	}	
	

	

	//vez do jogador 

//encerra o jogo
	}
}); 
	
	
	//ações dos botôes
	b1.addActionListener(new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent e) {
			play("b1");
		 jjogador +=0;

		
			
			
		}
	});
    b2.addActionListener(new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent e) {
			play("b2");
			jjogador += " "+1;
		
			
		}
	});
   b3.addActionListener(new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent e) {
			play("b3");
			jjogador += " "+2;
			
		}
	});
   b4.addActionListener(new ActionListener() {
		
		@Override
		public void actionPerformed(ActionEvent e) {
			play("b4");
			jjogador += " "+3;
			
		}
	});
   
 
   
  
  


}
 //  som no botão 
public void play(String audio){
	URL url = getClass().getResource(audio+".wav");
	AudioClip  audioc = Applet.newAudioClip(url);
    audioc.play();
}

	public void jlabe (){
		JLabel mPontos = new JLabel("pontos ");
		mPontos.setText("pontos :"+pontos);
		mPontos.setHorizontalAlignment(SwingConstants.CENTER);
		mPontos.setBounds(70, 200, 40, 40);
	}a
	public void contagem(){
		try {Thread.sleep(1000);} catch (InterruptedException e) {}
	}

}
`

D

estou fazendo o jogo gênius e para dar o efeito d botão piscando eu coloquei para em 2 segundo ele ficar e depois chamar outra tarefa para ele retornar a cor normal, foi a forma que encontrei para fazer isso

Jonas_B_a_r_r_o_s

Você pode tentar com Thread:

import java.awt.Color;

import java.awt.FlowLayout;

import static java.lang.Thread.sleep;

import javax.swing.JButton;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JFrame;

public class MinhaThread extends Thread {

public static void botao1() throws InterruptedException {
    System.out.println("Seu codigo aqui");
    sleep(4000);
}

public static void botao2() throws InterruptedException {
    System.out.println("Seu codigo aqui");
    sleep(4000);
} 


 public static void main(String[] args){
    JFrame tela = new JFrame("Tela principal");
    tela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    tela.setBounds(300, 300, 300, 300);
    tela.setBackground(Color.GREEN);
    tela.setResizable(false);
    tela.setLayout(new FlowLayout());        
    
    JButton b1 = new JButton("Botao 1");
    JButton b2 = new JButton("Botao 2");
    
    b1.addActionListener(new Botao1());
    b2.addActionListener(new Botao2());
    
    tela.add(b1);
    tela.add(b2);
    tela.setVisible(true);

}

public static class Botao1 implements ActionListener { 
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
             MinhaThread bot = new MinhaThread();
             bot.start();
             MinhaThread.botao1();
        } catch (InterruptedException ex) {
            
        }
    }
}

 public static class Botao2 implements ActionListener { 
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            MinhaThread bot = new MinhaThread();
            bot.start();
            MinhaThread.botao2();
        } catch (InterruptedException ex) {
            
        }
    }
}

}

Criado 9 de junho de 2016
Ultima resposta 9 de jun. de 2016
Respostas 4
Participantes 2