Socorro, chamar um frame automaticamente após 3 segundos

9 respostas
DANIEL35
Olá amigos, dessa vez preciso chamar um outro frame quando esse fechar, depois de 3 segundos, conforme eu determinei. Tenho uma tela de login, que precisa ser iniciada após a apresentação fechar. Por favor, alguém poderia me ajudar a entender onde chamar esta tela de login? Obrigado. Vejam o código:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.TimerTask; ;   
import java.util.Timer;   

class TelaIntroducao extends JFrame {
	public static final long TEMPO = (3000); 
    FontMetrics fm;
    String s = "Testes.......";
    
   public TelaIntroducao() {   	
    setTitle("TESTANDO");
    getContentPane().setLayout(new FlowLayout()); 
    
    
     Timer timer = null;      
         if (timer == null) {      
             timer = new Timer();    
                   
             TimerTask tarefa = new TimerTask() {   
      
                 public void run() {      
                     try {  
                                     System.exit(0);    
                                // new TelaLogar();       
                         System.out.println("Teste Agendador");      
                            
                     } catch (Exception e) {      
                         e.printStackTrace();      
                     }      
                 }      
             };      
             timer.scheduleAtFixedRate(tarefa, TEMPO, TEMPO);      
         } 
          
            //new TelaLogar();
  
    
    Font font = new Font("Jokerman", Font.ITALIC, 36);
    setFont(font);
    fm = getFontMetrics(font);
    setSize(fm.stringWidth(s)+30, fm.getHeight()+60);

    setVisible(true);
	setSize(550, 550);
	setResizable(false);
    setLocationRelativeTo(null);	

   }
   public void paint(Graphics g) {
      Insets ins = getInsets();
      int w = getSize().width-ins.left-ins.right;
      int h = getSize().height-ins.top-ins.bottom;

      int centerX = w/2 + ins.left;
      int centerY = h/2 + ins.top;

      g.setColor(Color.red);
      g.fillRect(ins.left, ins.top, w, h);

      g.setColor(Color.yellow);
      g.drawString(
         s, 
         centerX-fm.stringWidth(s)/2, 
         centerY + (fm.getAscent()-fm.getDescent())/2
      );
   }
   public static void main(String[] args){
   	new TelaIntroducao();
   }
}

9 Respostas

guisantogui

Apenas li o titulo to meio com pressa, mas algo como

Thread.sleep(3000);
janela.setVisible(true);

deve funcionar

Allan2M

Onde está

System.exit(0); System.out.println("Teste Agendador");
Coloque

new JanelaPrincipal(); //Manda iniciar a janela principal dispose(); //Desabilita a janela Testando...

Espero ter ajudado

DANIEL35
Primeiro, obrigado pela atenção, e na verdade o que está acontecendo é que ao rodar o código,a tela de apresentação some depois de 3 segundos, mas a janela de login que peço para ser iniciada, não para de aparecer. A cada 3 segundos surgi uma nova tela de login. Fiz alguns testes aqui mas não consegui descobrir como fazer parar de acontecer isso. Teria como dar essa ajuda? Obrigado. Veja o código:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.TimerTask; ;   
import java.util.Timer;   

class TelaIntroducao extends JFrame {
	public static final long TEMPO = (3000); 
    FontMetrics fm;
    String s = "Testesssss";
    
   public TelaIntroducao() {   	
    setTitle("TESTANDO");
    getContentPane().setLayout(new FlowLayout()); 
    
    
     Timer timer = null;      
         if (timer == null) {      
             timer = new Timer();    
                   
             TimerTask tarefa = new TimerTask() {   
      
                 public void run() {      
                     try {  
                          new TelaLogar(); 
			            dispose();   
                            
                     } catch (Exception e) {      
                         e.printStackTrace();      
                     }      
                 }      
             };      
             timer.scheduleAtFixedRate(tarefa, TEMPO,TEMPO);      
         }  
    
  
    
    Font font = new Font("Jokerman", Font.ITALIC, 36);
    setFont(font);
    fm = getFontMetrics(font);
    setSize(fm.stringWidth(s)+30, fm.getHeight()+60);

    setVisible(true);
	setSize(550, 550);
	setResizable(false);
    setLocationRelativeTo(null);	

   }
   public void paint(Graphics g) {
      Insets ins = getInsets();
      int w = getSize().width-ins.left-ins.right;
      int h = getSize().height-ins.top-ins.bottom;

      int centerX = w/2 + ins.left;
      int centerY = h/2 + ins.top;

      g.setColor(Color.red);
      g.fillRect(ins.left, ins.top, w, h);

      g.setColor(Color.yellow);
      g.drawString(
         s, 
         centerX-fm.stringWidth(s)/2, 
         centerY + (fm.getAscent()-fm.getDescent())/2
      );
   }
}
f4binho

Se liga:

public  void run() {        
                      try {    
                           new TelaLogar();   
                         dispose();     
                               
                      } catch (Exception e) {        
                          e.printStackTrace();        
                      }        
                  }

Da primeira vez que passar por esse código ele vai criar uma nova TelaLogar e dar o dispose no Frame

Mas da segunda vez que rodar ele vai fazer a mesma coisa, só que dessa vez o Frame não está disponível enton

A cada vez que rodar ele vai criar uma nova TelaLogar

DANIEL35
Sem chance, amigo. Depois que sobe a tela de introdução e no momento que ela desaparece (3 segundos), começa a surgir a cada 3 segundos uma nova tela de login... Não consigo entender!!! Já fiz diversos testes e estou quase desistindo. Veja o código:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.TimerTask; ;   
import java.util.Timer;   

class TelaIntroducao extends JFrame {
	public static final long TEMPO = (3000); 
    FontMetrics fm;
    String s = "PPI V: Academia Força Ativa";
    
   public TelaIntroducao() {   	
    setTitle("PPI-V");
 
    getContentPane().setLayout(new FlowLayout()); 
    
     Timer timer = null;      
         if (timer == null) {      
             timer = new Timer();    
                       
             TimerTask tarefa = new TimerTask() {   
 
                 public void run() { 
                       
                     try {
                     	    new TelaLogar();   
                            dispose();
                      }catch (Exception e){
                      	e.printStackTrace();     
                          
                     } 
                      		    
                 } 
                   
             };
                     
             timer.scheduleAtFixedRate(tarefa, TEMPO,TEMPO);
        }
		
    Font font = new Font("Jokerman", Font.ITALIC, 36);
    setFont(font);
    fm = getFontMetrics(font);
    setSize(fm.stringWidth(s)+30, fm.getHeight()+60);
		
    setVisible(true);
	setSize(550, 550);
	setResizable(false);
    setLocationRelativeTo(null);	

   }
   
   public void paint(Graphics g) {
 		
      Insets ins = getInsets();
      int w = getSize().width-ins.left-ins.right;
      int h = getSize().height-ins.top-ins.bottom;

      int centerX = w/2 + ins.left;
      int centerY = h/2 + ins.top;

      g.setColor(Color.red);
      g.fillRect(ins.left, ins.top, w, h);

      g.setColor(Color.yellow);
      g.drawString(
         s, 
         centerX-fm.stringWidth(s)/2, 
         centerY + (fm.getAscent()-fm.getDescent())/2
      );
         	
   }
}
f4binho

Então,

vc determinou o tempo de execução do seu timer em 3000 ms = 3 s. É o tempo em que a sua Thread faz um loop. E a cada 3 segundos vc está criando uma nova TelaLogar. É por isso que a cada 3 segundos aparece uma nova tela.

Entendeu???

new TelaLogar();
DANIEL35

Mas então o que deve ser feito para depois que a introdução sair, aparecer somente uma tela de logar?

f4binho

Pow vc pode criar uma lógica que após os 3 primeiros segundos ele dá o dispose no seu Frame, dá o new TelaLogar() e depois interromper a Thread. No Timer ele cria uma Thread e essa Thread vai dando seus loppings baseados no tempo que vc implementar.

Eu normalmente uso o Runnable, pois nunca parei pra usar o Timer :smiley: mas de qualquer forma, vc tem que interromper o looping da Thread.

DANIEL35

Vou tentar fazer essa mágica…

Criado 11 de junho de 2010
Ultima resposta 12 de jun. de 2010
Respostas 9
Participantes 4