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 7 of 7

Thread: Hello! Trying to Get Java Swing GUI to display clock/timer in jTextField

  1. #1
    Junior Member
    Join Date
    Jan 2011
    Posts
    3
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Question Hello! Trying to Get Java Swing GUI to display clock/timer in jTextField

    Hello,

    Please help! I'm relatively new to Java and trying to develop an app that include a time-dependent function:
    -at a specified time interval, a jTextField in a jFrame will update with the real time, thus displaying a digital clock
    -at the time interval, other code may be executed as well.

    I've found many clock apps online, and different approaches, and tried all kinds of approaches, but none perform this simple function other than as a standalone app. Spent many many hours over the last MONTH trying to figure this out, but now throw in the towel for the experts.

    There's a similar forum thread already going for the same/similar purpose titled "Updating timer".

    However, since the code included for that thread is not complete, I'm having trouble finding helpful clues.

    My latest coding attempt is given below. As you can see, the line:

    timer.scheduleAtFixedRate(updateText2(), delay, period);

    attempts to implement a method at the specified interval, with a delay. Any help and/or guidance would be greatly appreciated!

    package javaPracticeCode;
    import java.util.Timer;
    import java.util.TimerTask;
     
    public class SwingClockTest extends javax.swing.JFrame {
     
        /** Creates new form SwingClockTest */
        public SwingClockTest() {
            initComponents();
     
        }
     
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            jTextField1 = new javax.swing.JTextField();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jTextField1.setEditable(false);
            jTextField1.setText("jTextField1");
            jTextField1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    clockTextUpdate(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(24, 24, 24)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(317, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(258, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
     
        private void clockTextUpdate(java.awt.event.ActionEvent evt) {                                 
            // TODO add your handling code here:
        }                                
     
     
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    SwingClockTest poopstain = new SwingClockTest();
                    poopstain.setVisible(true);
                Timer timer = new Timer();
                timer.scheduleAtFixedRate(updateText2(), delay, period);
                }
            });
        }
        private final static int delay = 1000;
        private final static int period = 1000;
     
        public void run() {
            jTextField1.setText("Chicken Nipples!");
        }
        public static String updateText2()
        {
           int chicken = chicken +1;
            String updatedText = "chickens!"+chicken;
     
            return updatedText;
        }
        // Variables declaration - do not modify                     
        private javax.swing.JTextField jTextField1;
        // End of variables declaration                   
     
    }


  2. #2
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Hello! Trying to Get Java Swing GUI to display clock/timer in jTextField

    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  3. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Hello! Trying to Get Java Swing GUI to display clock/timer in jTextField

    JAVA is your best friend when it comes to not having to do the work yourself.

    I would advise looking into the GregorianCalendar object (GregorianCalendar (Java Platform SE 6)). Why this? Because this can give you the current time, day, day of week, ect. Really anything you want to know about dates or deal with dates can be done with the GregorianCalendar object.

    Here is a sample code to print out the current time(it is actually this easy):
    import java.util.GregorianCalendar;
     
    public class DateTesting
    {
        public static void main(String[] args)
        {
    		GregorianCalendar current = new GregorianCalendar();
    		System.out.println(current.get(GregorianCalendar.HOUR)+":"+current.get(GregorianCalendar.MINUTE));
        }
    }

    As for updating when the time changes, my first place to look would be if there is some sort of object that will throw an event when the time changes. If there is, then that could be an easy way of listening for a time change. Alternatively, you would want to put on a delay of 1 minute for, well I guess eternity. Doesn't seem like the best solution. I'm sure there is an elegant way of doing it.
    Last edited by aussiemcgr; January 25th, 2011 at 06:30 PM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  4. The Following User Says Thank You to aussiemcgr For This Useful Post:

    JavaNoob#5 (January 26th, 2011)

  5. #4
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Hello! Trying to Get Java Swing GUI to display clock/timer in jTextField

    Quote Originally Posted by aussiemcgr View Post
    As for updating when the time changes, my first place to look would be if there is some sort of object that will throw an event when the time changes. If there is, then that could be an easy way of listening for a time change. Alternatively, you would want to put on a delay of 1 minute for, well I guess eternity. Doesn't seem like the best solution. I'm sure there is an elegant way of doing it.
    How to Use Swing Timers (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Other Swing Features)
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  6. The Following User Says Thank You to KevinWorkman For This Useful Post:

    JavaNoob#5 (January 26th, 2011)

  7. #5
    Junior Member
    Join Date
    Jan 2011
    Posts
    3
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Hello! Trying to Get Java Swing GUI to display clock/timer in jTextField

    After considerable effort, I FINALLY managed to produce a working jTextField clock! Special thanks to online discussion forums like this.

    I wanted to share my solution, not only so that others trying the same thing can benefit from these open forum discussions, but so that other more savvy programmers might offer even BETTER approaches. For example, it might be worth trying the aforementioned Swing Timer class. Enjoy!

    This is the class which implements the running timing thread; it updates the text of a public static jTextField in another class; the GregorianCalendar import is not used for this code but I have it as a placeholder for further efforts:

     
    package javaPracticeCode;
     
    import java.util.GregorianCalendar;
    import java.util.*;
     
    public class TimerScript implements Runnable {
     
        Thread runner;
        public TimerScript(){
            start();
        }
     
             public String timeNow()
         {
           Calendar now = Calendar.getInstance();
           int hrs = now.get(Calendar.HOUR_OF_DAY);
           int min = now.get(Calendar.MINUTE);
           int sec = now.get(Calendar.SECOND);
     
           String time = zero(hrs)+":"+zero(min)+":"+zero(sec);
     
           return time;
         }
     
              public String zero(int num)
         {
           String number=( num < 10) ? ("0"+num) : (""+num);
           return number;                                    //Add leading zero if needed
     
         }
     
     
         public void start()
         {
           if(runner == null) runner = new Thread(this);
           runner.start();
                                                                 //method to start thread
         }
     
     
         public void run()
         {
     
           while (runner == Thread.currentThread() )
           {
            JFrameComboBox.jTextField2.setText(timeNow());
                                                             //define thread task
               try
                 {
                   Thread.sleep(1000);
                 }
                  catch(InterruptedException e)
                      {
                        System.out.println("Thread failed");
                      }
           }
         }
         public static void main(String [] args){
             TimerScript poop = new TimerScript();
         }
    }

    And this is the code for the JPanel with the actual jTextField clock:

     
    package javaPracticeCode;
     
    public class JFrameComboBox extends javax.swing.JFrame {
     
        /** Creates new form JFrameComboBox */
        public JFrameComboBox() {
            initComponents();
            TimerScript stain = new TimerScript();
            stain.run();
        }
     
        /** 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() {
     
            TestComboBox = new javax.swing.JComboBox();
            jTextField1 = new javax.swing.JTextField();
            jComboBox2 = new javax.swing.JComboBox();
            jTextField2 = new javax.swing.JTextField();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            TestComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "(none selected)", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }));
            TestComboBox.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    TestComboBoxActionPerformed(evt);
                }
            });
     
            jTextField1.setText("jTextField1");
     
            jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
     
            jTextField2.setText("jTextField2");
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(TestComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 144, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(jTextField2, javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jTextField1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 122, Short.MAX_VALUE))
                    .addContainerGap(90, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(28, 28, 28)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(TestComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(212, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>
     
        private void TestComboBoxActionPerformed(java.awt.event.ActionEvent evt) {                                             
            // TODO add your handling code here:
              //      JComboBox cb = (JComboBox)e.getSource();
            String month = (String)TestComboBox.getSelectedItem();
                    String monthInt = month;
     
            if(month == "1")
                jTextField1.setText("January");
            else if(month == "2")
                    jTextField1.setText("February");
            else if(month =="3")
                jTextField1.setText("March");
            else
                jTextField1.setText("Every month is a PARTY!");
     
        }                                            
     
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new JFrameComboBox().setVisible(true);
                }
            });
        }
     
        // Variables declaration - do not modify
        private javax.swing.JComboBox TestComboBox;
        private javax.swing.JComboBox jComboBox2;
        public javax.swing.JTextField jTextField1;
        public static javax.swing.JTextField jTextField2;
        // End of variables declaration
     
    }

  8. #6
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Hello! Trying to Get Java Swing GUI to display clock/timer in jTextField

    You got lucky because the setText() method is Thread safe, but when dealing with the GUI, you don't want to make changes to it on a Thread other than the EDT. A Swing Timer would have made this a non-issue, or you could use SwingUtilities to execute the code on the EDT.
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  9. The Following User Says Thank You to KevinWorkman For This Useful Post:

    JavaNoob#5 (January 28th, 2011)

  10. #7
    Junior Member
    Join Date
    Jan 2011
    Posts
    3
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Re: Hello! Trying to Get Java Swing GUI to display clock/timer in jTextField

    Figured out how to use the Swing timer and listener. That IS a lot better and simpler to do; thanks!

    The following is a link with a simple example of a jLabel clock:

    Timer: clock label : TimerSwing JFCJava

Similar Threads

  1. How to Use Timer in Java
    By neo_2010 in forum Java SE API Tutorials
    Replies: 2
    Last Post: August 6th, 2013, 09:49 AM
  2. Timer implementation in swing
    By portem1 in forum Algorithms & Recursion
    Replies: 1
    Last Post: January 19th, 2011, 08:14 AM
  3. Java dialog box is blank in 2nd attempt while using timer.
    By mocherla81 in forum AWT / Java Swing
    Replies: 1
    Last Post: January 17th, 2011, 09:49 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

Tags for this Thread