0

I will like to display a series of messages for few seconds and disappears during connection to DB. How do I do that in Java?

The first message should say "Connecting to database", the second message should say "creating a database" and the last message should say " database creation successful".

Here is the code of the class. I simply want to replace println statement with a pop up that closes it after few seconds.

  public class ExecuteSQL {

   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/?allowMultiQueries=true";

   //  Database credentials
   static final String USER = "root";
   static final String PASS = "";



public static void connectExe() {

        Connection conn = null;
           Statement stmt = null;

           try{

              Class.forName("com.mysql.jdbc.Driver");

              System.out.println("Connecting to database...");
              conn = DriverManager.getConnection(DB_URL, USER, PASS);

              System.out.println("Creating database...");
              stmt = conn.createStatement();

              String sql = Domain.getCurrentDatabaseSQL();
              stmt.executeUpdate(sql);
              System.out.println("Database created successfully...");


           }catch(SQLException se){
              se.printStackTrace();
           }catch(Exception e){
              e.printStackTrace();
           }finally{

              try{
                 if(stmt!=null)
                    stmt.close();
              }catch(SQLException se2){
              }
              try{
                 if(conn!=null)
                    conn.close();
              }catch(SQLException se){
                 se.printStackTrace();
              }
           }//end try

    }

}  

I'm using Swing.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Keffi John
  • 31
  • 4
  • 1
    A lot will come down to what you are using to display the message with, but the general idea would be to show the message and start a timer. When the timer fires, you would close the message – MadProgrammer Sep 20 '14 at 06:58
  • @AndrewThompson Sure, but with what framework? – MadProgrammer Sep 20 '14 at 07:06
  • @MadProgrammer: the question is tagged with `swing` so I would assume that is the framework in question –  Sep 20 '14 at 07:45
  • @a_horse_with_no_name I'm sure it wasn't when I posted the comment. :P – MadProgrammer Sep 20 '14 at 07:50
  • So.. in case you did not figure it out yet, use a Swing based [`Timer`](http://docs.oracle.com/javase/8/docs/api/javax/swing/Timer.html) (or possibly several, depending on the exact design). BTW - if this is about *actually* logging into a DB (as opposed to just simulating it as you described), it would be better to use a [`SwingWorker`](http://docs.oracle.com/javase/8/docs/api/javax/swing/SwingWorker.html). – Andrew Thompson Sep 20 '14 at 08:30
  • Okay, as an [example](http://stackoverflow.com/questions/13203415/how-to-add-fade-fade-out-effects-to-a-jlabel/13203744#13203744) – MadProgrammer Sep 20 '14 at 09:59
  • @AndrewThompson Oh, was it, thought it was using a `javax.swing.Timer` – MadProgrammer Sep 20 '14 at 21:16
  • @MadProgrammer One of us is confused, and I'm not sure who. My point was that this 'update label using *long running task*' was more for `SwingWorker`.. – Andrew Thompson Sep 21 '14 at 00:33
  • @AndrewThompson Quite possibly, need more sleep :P – MadProgrammer Sep 21 '14 at 02:44
  • So.. did you *solve* this problem? – Andrew Thompson Sep 23 '14 at 01:22
  • @Yes I did, using javax.swing.timer as MadProgrammer suggested. Thank you all for your suggestions – Keffi John Sep 25 '14 at 21:14

1 Answers1

1

There's a multitude of ways to actually show the message, you could use a JPanel on the glass pane, you could use a frameless window, you could...but lets not worry about that.

Probably the easiest and best way to trigger a future event in Swing is through the use of the javax.swing.Timer. It's simple and straight to use and is safe to use within in Swing.

Swing is not thread safe and is single threaded. This means that you should never block the Event Dispatching Thread with code that might take time to run or pause the execution of the EDT and you should never interact with the any of the UI components from outside of the EDT.

The javax.swing.Timer is a great way to wait for a specified period of time without blocking the EDT, but will trigger it's updates within the context of the EDT, making it easy to use and safe to interact with UI components from within...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class ShowMessage {

    public static void main(String[] args) {

        EventQueue.invokeLater(
                new Runnable() {
                    @Override
                    public void run() {
                        try {
                            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                        } catch (ClassNotFoundException ex) {
                        } catch (InstantiationException ex) {
                        } catch (IllegalAccessException ex) {
                        } catch (UnsupportedLookAndFeelException ex) {
                        }

                        final JFrame frame = new JFrame("Test");
                        frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                        frame.setLayout(new GridBagLayout());
                        ((JComponent)frame.getContentPane()).setBorder(new EmptyBorder(20, 20, 20, 20));
                        frame.add(new JLabel("Boo"));
                        frame.pack();
                        frame.setLocationRelativeTo(null);
                        frame.setVisible(true);

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

}

See Concurrency in Swing and How to Use Swing Timers for more details

Updated

If you're running a background of unknown length, you can use a SwingWorker instead. This will allow you to run the task in the doInBackground method and when completed, the done method will be called and you can close the message popup

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366