Using a Timer in Swing to display a picture for 5 seconds

时光毁灭记忆、已成空白 提交于 2021-02-17 05:19:45

问题


I am trying to make a login picture for my application using Timer. The idea is, when the user opens the application, he will see a picture for 5 seconds, then the application will start.

I tried, as you can see in the method shoutoff():

     /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package login;


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

/**
 *
 * @author isslam
 */

public class login extends javax.swing.JFrame {
 Timer time;
    /**
     * Creates new form login
     */

    public login() {
        initComponents();
        setLocation(350, 200);
         time = new Timer(5000,new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
              dispose();
         }
     });
     time.setRepeats(false);

    }
 public void shoutoff(){
if (!time.isRunning()) {
        time.start();
    }
 }
    /**
     * 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() {

        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setAlwaysOnTop(true);
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setLocationByPlatform(true);
        setUndecorated(true);
        setResizable(false);

        jLabel1.setIcon(new javax.swing.ImageIcon("C:\\Users\\isslam\\Desktop\\one_piece_marble_play_by_iviarker-d511vb0.jpg")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1)
        );

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

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new login().setVisible(true);
               new login().shoutoff();
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JLabel jLabel1;
    // End of variables declaration                   
}

回答1:


Start by creating the Timer once in the constructor. The Timer should, also, only make the CURRENT instance of login close

public login() {
    //...
    time = new Timer(5000,new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
              dispose();
         }
     });
     timer.setRepeats(false);
}

In the shoutoff method, you start timer...

public void shoutoff(){
    if (!time.isRunning()) {
        timer.start();
    }
}

Take a closer look at How to use Swing Timers for more details.

You might like to have a read through Code Conventions for the Java TM Programming Language, it will make it easier for people to read your code and for you to read others




回答2:


The idea is, when the user opens the application, he will see a picture for 5 seconds, then the application will start.

You should use a Splash Screen. The advantage of the splash screen is the image is displayed immediately as the whole Swing app doesn't need to be loaded.

Check out the section from the Swing tutorial on How to Create a Splash Screen for more information and a working example.



来源:https://stackoverflow.com/questions/29906378/using-a-timer-in-swing-to-display-a-picture-for-5-seconds

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!