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

Thread: Swing Timers

  1. #1
    Junior Member
    Join Date
    May 2009
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Swing Timers

    Hi I have a program that should bring up two JTextFields, one with a phrase in it and the other empty. I want it to then wait 5 seconds to give the user time to enter in the translated answer. Then it should compare the two fields and give a response. This is the code I have now -
    package languagestudy;
     
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Scanner;
    import javax.swing.*;
     
    /**
     *Sterling McLeod
     */
     
     
    public class LanguageStudy {
     
        public JFrame frame;
        public JPanel panel;
        public JTextField toTranslate;
        public JTextField translated;
        public ArrayList<String> phrases;
        public Scanner scan;
        public Random rng = new Random();
        public Timer timer;
     
     
        public LanguageStudy(String language) throws IOException{
            if(language.equalsIgnoreCase("spanish")) {  //check what language and get phrases for appropriate language
               String file = "C:/Users/Sterling/Documents/NetBeansProjects/LanguageStudy/Spanish.txt";
               getPhrases(file);
            }
        }
     
        public void createAndShowGUI() {    //make two text fields
            frame = new JFrame("LanguageStudy!");
            panel = new JPanel();
            toTranslate = new JTextField(40);
            translated = new JTextField(40);
            panel.add(toTranslate);
            panel.add(translated);
            panel.setVisible(true);
            frame.add(panel);
            frame.pack();
            frame.setVisible(true);
        }
     
        public void getPhrases(String theFile) throws IOException{
            phrases = new ArrayList<String>();
            File file = new File(theFile);
            scan = new Scanner(file);    //make a scanner for the file
            scan.useDelimiter("\r?\n|\r");
            int count = 0;
            while(scan.hasNext()) { //get amount of phrases
                phrases.add(scan.next());
                count++;
            }
        }
     
        public void go() {  //starts program
            System.out.println("How many seconds would you like the timer to be?");
            Scanner scan2 = new Scanner(System.in);
            int time = scan2.nextInt() * 1000;
            timer = new Timer(time, new TimeListener());    //set timer
            createAndShowGUI();
            timer.start();
        }
     
     
        class TimeListener implements ActionListener {
     
            public void actionPerformed(ActionEvent e) {
                int a = rng.nextInt(phrases.size());    //get a random number
                JOptionPane.showMessageDialog(null, "A new phrase awaits you.");    //notify user
                toTranslate.setText(phrases.get(a));    //set text to the random phrase
                //PROGRAM SHOULD WAIT HERE TO COMPARE THE TWO FIELDS!!!!!!!
                if(a % 2 == 0) {    //if toTranslate was english
                    if(translated.getText().equalsIgnoreCase(phrases.get(a+1))) {
                        JOptionPane.showMessageDialog(null, "Correct!");
                    }
                    else {
                        String right = "Sorry the answer is " + phrases.get(a+1);
                        JOptionPane.showMessageDialog(null, right);
                    }   //end inner if-else
                }
                else if(a % 2 == 1) {   //if toTranslate was foreign
                    if(translated.getText().equalsIgnoreCase(phrases.get(a-1))) {
                        JOptionPane.showMessageDialog(null, "Correct!");
                    }
                    else {
                        String right = "Sorry the answer is " + phrases.get(a-1);
                        JOptionPane.showMessageDialog(null, right);
                    }   //end inner if-else
     
                }   //end if-else
            }   //end actionPerformed
     
        }   //end class TimeListener
     
        public static void main(String[] args) throws IOException{
            LanguageStudy study = new LanguageStudy("spanish");
            study.go();
        }
     
    }

    The main problem I am having is that I don't know how to say "wait 5 seconds before continuing." It just puts up a new phrase, and compares instantly. Another small issue I am having is when I first run it, both the fields are blank and it doesn't start until the time has passed by once. Any help would be appreciated.


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,302
    Thanks
    181
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: Swing Timers

    You should initiate the text box prior to starting the TimeListener, otherwise nothing will happen until after you've listened for the specified time. So:
                int a = rng.nextInt(phrases.size());    //get a random number
                JOptionPane.showMessageDialog(null, "A new phrase awaits you.");    //notify user
                toTranslate.setText(phrases.get(a));    //set text to the random phrase
    should be placed in your go() method. When you start the timer it will wait the specified time, then run the actionPerformed method to check the answer. If you wish to continue as a loop, place the above code at the end of the actionPerformed method as wellk, and then create and start another timer

  3. #3
    Junior Member
    Join Date
    May 2009
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Swing Timers

    Well I got the program to start looping with Thread.sleep(5000). The problem I am having now is that when the JTextFields come up, I am unable to set my cursor there. It's like grabFocus() just isn't working.
    package languagestudy;
     
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Scanner;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
     
    /**
     *Sterling McLeod
     */
     
     
    public class LanguageStudy {
     
        public JFrame frame;
        public JPanel panel;
        public JTextField toTranslate;
        public JTextField translated;
        public ArrayList<String> phrases;
        public Scanner scan;
        public Random rng = new Random();
        public Timer timer;
     
        public LanguageStudy(String language) throws IOException{
            if(language.equalsIgnoreCase("spanish")) {  //check what language and get phrases for appropriate language
               String file = "C:/Users/Sterling/Documents/NetBeansProjects/LanguageStudy/Spanish.txt";
               getPhrases(file);
            }
        }
     
        public void createAndShowGUI() {    //make two text fields
            frame = new JFrame("LanguageStudy!");
            panel = new JPanel();
            toTranslate = new JTextField(40);
            translated = new JTextField(40);
            panel.add(toTranslate);
            panel.add(translated);
            panel.setVisible(true);
            frame.add(panel);
            frame.pack();
            frame.setVisible(true);
        }
     
        public void getPhrases(String theFile) throws IOException{
            phrases = new ArrayList<String>();
            File file = new File(theFile);
            scan = new Scanner(file);    //make a scanner for the file
            scan.useDelimiter("\r?\n|\r");
            int count = 0;
            while(scan.hasNext()) { //get amount of phrases
                phrases.add(scan.next());
                count++;
            }
        }
     
        public void go() {  //starts program
            System.out.println("How many seconds would you like the timer to be?");
            Scanner scan2 = new Scanner(System.in);
            int delay = scan2.nextInt() * 1000;
            createAndShowGUI();
            Timer timer = new Timer(delay, new TimeListener());    //set timer
            timer.setInitialDelay(0);
            timer.start();
        }
     
     
        class TimeListener implements ActionListener {
     
            public void actionPerformed(ActionEvent e) {
            int a = rng.nextInt(phrases.size());    //get a random number
            toTranslate.setText(phrases.get(a));    //set text to the random phrase
            JOptionPane.showMessageDialog(null, "A new phrase awaits you.");    //notify user
            translated.grabFocus();
                try {
                    Thread.sleep(5000); //give the user time to answer
                } catch (InterruptedException ex) {}
                if(a % 2 == 0) {    //if toTranslate was english
                    if(translated.getText().equalsIgnoreCase(phrases.get(a+1))) //if translated is equal to the next phrase (aka if correct foreign)
                        JOptionPane.showMessageDialog(null, "Correct!");
                    else {
                        String right = "Sorry the answer is " + phrases.get(a+1);
                        JOptionPane.showMessageDialog(null, right);
                    }   //end inner if-else
                }
                else if(a % 2 == 1) {   //if toTranslate was foreign
                    if(translated.getText().equalsIgnoreCase(phrases.get(a-1))) {   //if translated is equal to previous phrase (aka if correct english)
                        JOptionPane.showMessageDialog(null, "Correct!");
                    }
                    else {
                        String right = "Sorry the answer is " + phrases.get(a-1);
                        JOptionPane.showMessageDialog(null, right);
                    }   //end inner if-else
     
                }   //end if-else
            }   //end actionPerformed
     
        }   //end class TimeListener
     
        public static void main(String[] args) throws IOException{
            LanguageStudy study = new LanguageStudy("spanish");
            study.go();
        }
     
    }

    There is the whole code although I'm almost certain the problem is in actionPerformed. I don't see why I am unable to select the TextFields during the Thread.sleep(5000).

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,302
    Thanks
    181
    Thanked 824 Times in 767 Posts
    Blog Entries
    5

    Default Re: Swing Timers

    Quote Originally Posted by Sterzerkmode View Post
    Well I got the program to start looping with Thread.sleep(5000). The problem I am having now is that when the JTextFields come up, I am unable to set my cursor there. It's like grabFocus() just isn't working.
    .
    Did you try my original suggestion? Using Thread.sleep in this fashion means you are locking up the program for 5 seconds (the actionPerformed occurs in the Event Dispatch Thread (EDT) - and because all GUI interaction occurs in the EDT making it sleep means nothing else can happen until it stops sleeping). If you want to do it this way you need to spawn another thread, but that shouldn't be necessary. You just need to update the gui, then start the timer (rather than waiting for the timer to fire before updating the gui)

  5. #5
    Junior Member
    Join Date
    May 2009
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Swing Timers

    Ah okay I got it working. I read your post wrong the first time so it wasn't really working for me the first time I tried. But it works now. Thanks a lot for the help!

  6. #6
    Junior Member
    Join Date
    May 2009
    Posts
    12
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Swing Timers

    Okay well I had to where every x amount of time it would compare, and a new word would put up. But ideally, I'd like to set the amount of time between phrase changes and compare the new words after ten seconds. I tried adding a new listener, but it never compares the to. It will just sit there until it's time to change the phrases and changes them.

    package languagestudy;
     
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Scanner;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
     
    /**
     *Sterling McLeod
     */
     
     
    public class LanguageStudy {
     
        public JFrame frame;
        public JPanel panel;
        public JTextField toTranslate;
        public JTextField translated;
        public ArrayList<String> phrases;
        public Scanner scan;
        public Random rng = new Random();
        public Timer timer;
        public int a;
     
        public LanguageStudy(String language) throws IOException{
            if(language.equalsIgnoreCase("spanish")) {  //check what language and get phrases for appropriate language
               String file = "C:/Users/Sterling/Documents/NetBeansProjects/LanguageStudy/Spanish.txt";
               getPhrases(file);
            }
        }
     
        public void createAndShowGUI() {    //make two text fields
            frame = new JFrame("LanguageStudy!");
            panel = new JPanel();
            toTranslate = new JTextField(40);
            translated = new JTextField(40);
            panel.add(toTranslate);
            panel.add(translated);
            panel.setVisible(true);
            frame.add(panel);
            frame.pack();
            frame.setVisible(true);
        }
     
        public void getPhrases(String theFile) throws IOException{
            phrases = new ArrayList<String>();
            File file = new File(theFile);
            scan = new Scanner(file);    //make a scanner for the file
            scan.useDelimiter("\r?\n|\r");
            int count = 0;
            while(scan.hasNext()) { //get amount of phrases
                phrases.add(scan.next());
                count++;
            }
        }
     
        public void go() {  //starts program
            System.out.println("How many seconds would you like the timer to be?");
            Scanner scan2 = new Scanner(System.in);
            int delay = scan2.nextInt() * 1000;
            createAndShowGUI();
            Timer changeTimer = new Timer(delay, new ChangeListener());    //set timer
     
            //set the GUI before starting the timer
            a = rng.nextInt(phrases.size());    //get a random number
            toTranslate.setText(phrases.get(a));    //set text to the random phrase
            JOptionPane.showMessageDialog(null, "A new phrase awaits you.");    //notify user
            translated.requestFocusInWindow();
            //done setting up GUI
     
            changeTimer.start();
        }
     
     
        class ChangeListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
            translated.setText("");
            a = rng.nextInt(phrases.size());    //get a random number
            toTranslate.setText(phrases.get(a));    //set text to the random phrase
            JOptionPane.showMessageDialog(null, "A new phrase awaits you.");    //notify user
            translated.requestFocusInWindow();
            Timer compareTimer = new Timer(10000, new CompareListener());
            compareTimer.start();
            }   //end actionPerformed
        }   //end changeListener
     
        class CompareListener implements ActionListener {
     
            public void actionPerformed(ActionEvent e) {
     
            if(a % 2 == 0) {    //if toTranslate was english
                    if(translated.getText().equalsIgnoreCase(phrases.get(a+1))) //if translated is equal to the next phrase (aka if correct foreign)
                        JOptionPane.showMessageDialog(null, "Correct!");
                    else {
                        String right = "Sorry the answer is \"" + phrases.get(a+1) + "\"";
                        JOptionPane.showMessageDialog(null, right);
                    }   //end inner if-else
                }
                else if(a % 2 == 1) {   //if toTranslate was foreign
                    if(translated.getText().equalsIgnoreCase(phrases.get(a-1))) {   //if translated is equal to previous phrase (aka if correct english)
                        JOptionPane.showMessageDialog(null, "Correct!");
                    }
                    else {
                        String right = "Sorry the answer is \"" + phrases.get(a-1) + "\"";
                        JOptionPane.showMessageDialog(null, right);
                    }   //end inner if-else
     
                }   //end if-else
            }   //end actionPerformed
     
        }   //end class compareListener
     
        public static void main(String[] args) throws IOException{
            LanguageStudy study = new LanguageStudy("spanish");
            study.go();
        }
     
    }

    What am I missing here?
    Last edited by Sterzerkmode; November 10th, 2009 at 08:11 PM. Reason: some outdated comments

Similar Threads

  1. How to Add ActionListener to a JButton in Swing?
    By JavaPF in forum Java Swing Tutorials
    Replies: 17
    Last Post: April 24th, 2013, 05:14 PM
  2. How to Use a JSlider - Java Swing
    By neo_2010 in forum Java Swing Tutorials
    Replies: 4
    Last Post: March 29th, 2010, 09:33 AM
  3. java swing help
    By JM_4ever in forum AWT / Java Swing
    Replies: 3
    Last Post: October 7th, 2009, 06:42 AM
  4. Help - Swing Timer, 2 KeyEvents
    By Gheta in forum AWT / Java Swing
    Replies: 2
    Last Post: July 29th, 2009, 02:46 PM
  5. How to Use the JList component - Java Swing
    By neo_2010 in forum Java Swing Tutorials
    Replies: 1
    Last Post: July 11th, 2009, 04:02 AM