Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Swing Timer and Java Noob

  1. #1
    Junior Member
    Join Date
    Sep 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Swing Timer and Java Noob

    I'm trying to teach myself Java (for the past week). Anyway, I have a JFrame with a six text areas (each inside a scrollpane). Each text area is populated by running a query on a local access db and posting the results to that area. Currently, to do this, I just have a refresh button that, when clicked, goes to an event which calls all of the individual private voids that query / update the text areas. The source is like this (I'm going to leave some of the bulk out):

    This is the code I have been trying... First off I don't see why Thead.sleep is necessary (I'm unsure what it does), and second no matter where I place my timer code, I can't get it to work. I just don't understand where to place it. I'm not sure how to trigger it...I would like it to to be able to click a begin button once and then have it update every 5 minutes or something. I've tried it every way I can think of. Any ideas ?


     
            ActionListener taskPerformer = new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    UpdateProdAreaOne();
                    UpdateProdAreaTwo();
                    UpdateProdAreaThree();
                    UpdateProdAreaFour();
                    UpdateProdAreaFive();
                    UpdateProdAreaSix();
                }
            Timer timer = new Timer( 1000 , taskPerformer);
            //timer.setRepeats(false);
            timer.start();
     
            Thread.sleep(5000);
                };




    import java.sql.*;
    import java.util.Set;
    import javax.swing.JOptionPane;
    import javax.swing.JTable;
    import javax.swing.Timer;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableModel;
    import java.awt.event.*;
     
    public class DBMonitor extends javax.swing.JFrame {
     
        public DBMonitor() {
            initComponents();
        }
     
        private void RefreshButtonActionPerformed(java.awt.event.ActionEvent evt) {                                              
     
            UpdateProdAreaOne();
            UpdateProdAreaTwo();
            UpdateProdAreaThree();
            UpdateProdAreaFour();
            UpdateProdAreaFive();
            UpdateProdAreaSix();
     
        }               
     
        private void UpdateProdAreaOne() {
            //This is an example..there are 5 others like this
            //Query
            //Post results
        }
     
        public static void main(String args[]) {
            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(DBMonitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(DBMonitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(DBMonitor.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(DBMonitor.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 DBMonitor().setVisible(true);
                }
            });
        }
     
    //Variable Declarations
    //...no need to post unless wanted


  2. #2
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Swing Timer and Java Noob

    Yes, you are right -- a Thread.sleep(...) as no business being there, so get rid of it. Next -- why are you using a Swing Timer here in the first place? What purpose does it serve in this code? Finally, for us to best help you, I think you'll need to tell us more about your problem.

  3. #3
    Junior Member
    Join Date
    Sep 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Swing Timer and Java Noob

    Thanks for the reply! I wanted to use a timer so that the bits of code that update the database will run at a regular interval. I just can't figure out how to get the timer to work... This is how I want to to work: Press a button ("begin" or whatever) on the form. This runs the database queries and posts the data. It also starts a timer that will re-execute the database queries and post the data every five minutes. I am just not familiar with Java yet.


    Edit: It's like the displays in airports. The big screens that tell you about flight numbers and arrival times and such update every so often. I've seen airport screens with SQL errors lol.
    Last edited by hypnotoad; October 3rd, 2012 at 10:07 PM.

  4. #4
    Junior Member
    Join Date
    Sep 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Swing Timer and Java Noob

    Is part of the problem the way I have the program designed? Like I said, I'm very new. Should I put the bits of code that retrieve information from the db into separate classes? Perhaps in the "public static void main(String args[]) {" area? :\

  5. #5
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Swing Timer and Java Noob

    Yes, the database code should be in different classes, and no, not in the main method. You will want to read up on creating and using classes as well as OOP principles.

  6. #6
    Junior Member
    Join Date
    Sep 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Swing Timer and Java Noob

    Thank you curmudgeon, I've been trying to do some reading. I'm just short on time unfortunately. I'll try to separate the code into different classes and see what happens.

  7. #7
    Super Moderator curmudgeon's Avatar
    Join Date
    Aug 2012
    Posts
    1,130
    My Mood
    Cynical
    Thanks
    64
    Thanked 140 Times in 135 Posts

    Default Re: Swing Timer and Java Noob

    Quote Originally Posted by hypnotoad View Post
    Thank you curmudgeon, I've been trying to do some reading. I'm just short on time unfortunately. I'll try to separate the code into different classes and see what happens.
    Good. This also will help you be able to debug and test smaller units of code in isolation from other code which is always a good thing. If you do this, then you'll also want to take care that the database portion of the code does not get called on the Swing event thread, also known as the Event Dispatch Thread or EDT. Consider using SwingWorkers for this so that you can have code run background to the EDT, and yet be able to update Swing components on the EDT.

    Also regarding Timers -- if the code being run from the timer is mainly Swing code, that is, if it should run on the Swing event thread, then by all means use a Swing Timer. If on the other hand you'll be initiating database interaction from the Timer and will only be using Swing for displaying the updated information, then consider using a java.util.Timer and not a Swing Timer (javax.swing.Timer). Another option (sorry if this all confuses you) is to use a java.util.concurrent.ScheduledExecutorService which is a little more versatile than a java.util.Timer. Again if you go either of these routes, make sure to queue any Swing calls on the EDT. This can be done by creating a Runnable and passing it onto a SwingUtilities.invokeLater(...) method:

    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        // code that needs to be called on the Swing event thread goes here
      }
    });

  8. #8
    Junior Member
    Join Date
    Sep 2012
    Posts
    11
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Swing Timer and Java Noob

    That's really interesting. I'll definitely have to check on those other options. Right now though, I think I need to get everything working in separate classes and then try to use timers. I've never taken a programming class...I wish I had taken some of those instead of chemistry classes!!

Similar Threads

  1. Replies: 2
    Last Post: January 6th, 2012, 10:50 PM
  2. Replies: 6
    Last Post: January 28th, 2011, 01:13 AM
  3. Timer implementation in swing
    By portem1 in forum Algorithms & Recursion
    Replies: 1
    Last Post: January 19th, 2011, 08:14 AM
  4. Anyone familiar with the swing timer?
    By BigJoe in forum AWT / Java Swing
    Replies: 5
    Last Post: December 28th, 2010, 12:15 PM
  5. Help - Swing Timer, 2 KeyEvents
    By Gheta in forum AWT / Java Swing
    Replies: 2
    Last Post: July 29th, 2009, 02:46 PM