Olá amigos. Mais uma vez estou aqui solicitando a ajuda de vocês. Gostaria de fazer o frame que criei, fechar com uns 3 ou 5 segundos e logo em seguida já abrir uma outra tela de login que também já criei. Este frame que deverá fechar com uma espécie de um temporizador, será uma abertura do programa que criei e logo em seguida aparecerá uma tela de login. Como faria isso? Alguém de muito boa vontade poderia me ajudar?
Vejam o código:
[code]import java.awt.;
import javax.swing.;
import java.awt.event.*;
class TelaIntroducao extends JFrame {
FontMetrics fm;
String s = “PROGRAMA X…”;
public TelaIntroducao() {
setTitle(“TESTES”);
getContentPane().setLayout(new FlowLayout());
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
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
);
}
}[/code]
Você pode criar uma thread para controlar seu Frame. A thread se encarregaria de fechá-lo após x segundos.
Pelo que entendi você quer criar tipo aquela telinha (tem um nome específico, mas não me lembro no momento) que aparece enquanto o Netbeans está abrindo. Para esses casos, sei que o Java possui um recurso para isso, mas não me lembro o nome da classe.
Exatamente isso. Quero criar uma tela do tipo quando iniciamos o word, por exemplo, em que ela diz a versão do aplicativo e já logo encerra e abre o editor de texto, entendeu? É só uma apresentação do meu programa e depois já inicia a tela de login, que já criei.
Beleza!!! Então agora é só estudar SplashScreen.
Na verdade, esse recurso no Java 6 em diante é automático. Você não precisa nem programar código, e nem usar essa classe:
http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/splashscreen/
Correto, vou fazer e logo postarei o resultado.
Executei esse código mas não aconteceu nada… O que fiz de errado, então? Teria como explicar, pois não entendi como usar a classe SplashScreen.
[code]import java.awt.;
import java.awt.event.;
public class Teste extends Frame implements ActionListener {
static void renderSplashFrame(Graphics2D g, int frame) {
final String[] comps = {“foo”, “bar”, “baz”};
g.setComposite(AlphaComposite.Clear);
g.fillRect(120,140,200,40);
g.setPaintMode();
g.setColor(Color.BLACK);
g.drawString(“Loading “+comps[(frame/5)%3]+”…”, 120, 150);
}
public Teste() {
super(“SplashScreen demo”);
setSize(300, 200);
setLayout(new BorderLayout());
Menu m1 = new Menu(“File”);
MenuItem mi1 = new MenuItem(“Exit”);
m1.add(mi1);
mi1.addActionListener(this);
this.addWindowListener(closeWindow);
MenuBar mb = new MenuBar();
setMenuBar(mb);
mb.add(m1);
final SplashScreen splash = SplashScreen.getSplashScreen();
if (splash == null) {
System.out.println("SplashScreen.getSplashScreen() returned null");
return;
}
Graphics2D g = splash.createGraphics();
if (g == null) {
System.out.println("g is null");
return;
}
for(int i=0; i<100; i++) {
renderSplashFrame(g, i);
splash.update();
try {
Thread.sleep(90);
}
catch(InterruptedException e) {
}
}
splash.close();
setVisible(true);
toFront();
}
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
private static WindowListener closeWindow = new WindowAdapter(){
public void windowClosing(WindowEvent e){
e.getWindow().dispose();
}
};
public static void main (String args[]) {
Teste test = new Teste();
}
}[/code]
Você incluiu a classe no .jar?
Não. Mas então ela só funcionará se eu construir um .jar? Se executar no JCreator, como sempre faço, não dará certo?
Daniel, vc pode fazer o seguinte kra, criar uma classe que ele conta os segundos fiz isso a algum tempo atrás da uma olhada no codigo:
[code]
import java.util.Timer;
import java.util.TimerTask;
public class principal extends javax.swing.JFrame {
public static final long TEMPO = (1000 * 60); // atualiza a cada 1 minuto, pode trocar 60 por 3 que o caso do segundos que vc vai usar//
/** Creates new form principal_2 */
public principal() {
initComponents();
//****INICIA A TAREFA ELE VERIFICA A CADA UM MINUTO****//
System.out.println("inicio");
Timer timer = null;
if (timer == null) {
timer = new Timer();
TimerTask tarefa = new TimerTask() {
public void run() {
try {
//chama o metodo ou janela, como por exemplo new janela.show();
System.out.println("Teste Agendador");
} catch (Exception e) {
e.printStackTrace();
}
}
};
timer.scheduleAtFixedRate(tarefa, TEMPO, TEMPO);
}
}
/** 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() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new principal().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
}[/code]
Só uma coisa, esse código é de um frame pode jogar sua figura de apresentação nele e tallz, depois na hora de chamar o metodo vc chama sua janela de login e um this.dispose para fechar a janela de apresentação!!!
Qualquer dúvida poste ai!!
Certo, mas onde eu pediria para o código chamar minha tela de login? Fiz uns testes aqui, mas não consegui perceber isso.
Veja:
[code]/*
- principal_2.java
-
- Created on 17 de Maio de 2010, 14:14
*/
import java.util.TimerTask; ;
import java.util.Timer;
public class Principal extends javax.swing.JFrame {
public static final long TEMPO = (3000); // atualiza o site a cada 1 minuto
/** Creates new form principal_2 */
public Principal() {
initComponents();
//****INICIA A TAREFA ELE VERIFICA A CADA UM MINUTO****//
System.out.println("inicio");
Timer timer = null;
if (timer == null) {
timer = new Timer();
TimerTask tarefa = new TimerTask() {
public void run() {
try {
System.exit(0);
// new TelaLogar();
//chama o metodo ou janela, como por exemplo new janela.show();
System.out.println("Teste Agendador");
} catch (Exception e) {
e.printStackTrace();
}
}
};
timer.scheduleAtFixedRate(tarefa, TEMPO, TEMPO);
}
}
/** 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() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Principal().setVisible(true);
}
});
}
// Variables declaration - do not modify
// End of variables declaration
} [/code]
Beleza, o código fez meu frame de apresentação fechar no tempo que determinei.
Num sistema que eu estou fazendo para uma possível venda, eu apenas desabilitei a janela.
É funcional no meu caso pois é uma tela de cadastro principal e outra de suporte bem simples.
jFSuporte.setVisible(false);
//e na principal
jbSairActionPerformed(java.awt.eventt.ActionEvent evt){
System.exit(0);
}