Results 1 to 15 of 15
  1. #1
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default Program doesn't display anything

    Hi, I want my program to bring up two JTextFields. One is empty and the other has a string of text to be translated. I want the program to wait five seconds, compare the two JTextFields, and either tell the user they are right or wrong (with right answer). The program should then wait a specified time to bring up a new phrase. Whenever I run the program, nothing happens. Here is the code

    Java Code:
    package languagestudy;
    
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Random;
    import java.util.Scanner;
    import javax.swing.*;
    
    /**
     *Sterling McLeod
     */
    
    
    public class LanguageStudy {
    
        public JPanel panel;
        public JTextField toTranslate;
        public JTextField translated;
        public String[] phrases;
        public Scanner scan;
        public Random rng = new Random();
        public Timer timer;
    
    
        public LanguageStudy(String language) {
            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
            panel = new JPanel();
            toTranslate = new JTextField(40);
            translated = new JTextField(40);
            panel.add(toTranslate);
            panel.add(translated);
            panel.setVisible(true);
        }
    
        public void getPhrases(String theFile) {
            scan = new Scanner(theFile);    //make a scanner for the file
            int count = 0;
            while(scan.hasNext()) { //get amount of phrases
                count++;
            }
            phrases = new String[count];    //make array of strings for count
        }
    
        public void go() {  //starts program
            System.out.println("How long would you like the timer to be?");
            int time = scan.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.length);    //get a random number
                JOptionPane.showMessageDialog(null, "A new phrase awaits you.");    //notify user
                toTranslate.setText(phrases[a]);    //set text to the random phrase
                timer.setDelay(5000);   //delay 5 seconds to give chance to answer
                if(a % 2 == 0) {    //if toTranslate was english
                    if(translated.getText().equalsIgnoreCase(phrases[a+1])) {
                        JOptionPane.showMessageDialog(null, "Correct!");
                    }
                    else {
                        String right = "Sorry the answer is " + phrases[a+1];
                        JOptionPane.showMessageDialog(null, right);
                    }   //end inner if-else
                }
                else if(a % 2 == 1) {   //if toTranslate was foreign
                    if(translated.getText().equalsIgnoreCase(phrases[a-1])) {
                        JOptionPane.showMessageDialog(null, "Correct!");
                    }
                    else {
                        String right = "Sorry the answer is " + phrases[a-1];
                        JOptionPane.showMessageDialog(null, right);
                    }   //end inner if-else
    
                }   //end if-else
            }   //end actionPerformed
    
        }   //end class TimeListener
    
        public static void main(String[] args) {
            LanguageStudy study = new LanguageStudy("spanish");
            study.go();
        }
    
    }
    Basically in the constructor, I want to determine what language to use (I only have spanish now testing). Then go to a file and get the phrases that are set up like this -

    ENGLISH PHRASE
    FOREIGN PHRASE
    ENGLISH PHRASE
    FOREIGN PHRASE
    ENGLISH PHRASE
    FOREIGN PHRASE

    Then I call go(). go() should ask how long to set the timer, set the timer, display the GUI, and start running.

    But like I said, the program does nothing when I run it. Just has a loading bar until I terminate. Any ideas as to why?

  2. #2
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    Okay well I put a system.out displaying count's value in the while loop. The while is looping infinitely. Am I using .hasNext() wrong?

  3. #3
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    Quote Originally Posted by Chasingxsuns View Post
    Okay well I put a system.out displaying count's value in the while loop. The while is looping infinitely. Am I using .hasNext() wrong?
    Yes, hasNext doesn't advance the "cursor" at all, it only returns whether there is another token at the current position.

    Usually you do this:

    Java Code:
    while (scan.hasNext()) {
    	String next = scan.next();
    	
    	// do something with next
    }
    Note, this works for hasNext/next as well as all the other methods in Scanner.


    However, in your code, you only keep a count, so there's no need to store the return from scan.next(). However, you still need to call scan.next() - to advance the "cursor".

    BTW, do you not want to do anything with "next"?
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  4. #4
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    I changed it now to this -
    Java Code:
    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
            int count = 0;
            while(scan.hasNext()) { //get amount of phrases
                phrases.add(scan.next());
                System.out.println(phrases.get(count));
                count++;
            }
        }
    phrases is now an Arraylist<String> rather than String[]. Another question though is how do I say "Don't count " " as a delimiter?" Scan will count a space as a delimiter when I only want a newline to be a delimiter.

  5. #5
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    The Scanner class has a scanner.useDelimiter(String pattern) method. Specify a regular expression to use as the delimiter.

    Now, when you say "newline" do you mean "\n", or do you mean the line separator for the OS, which is "\n" (for unix) and "\r\n" (for windows). I believe it's "\r" for Mac, but it might be "\n", not sure. Use System.getProperty("line.separator"), which automatically uses the correct one for the OS the program is running.

    Or, do you want to match the newline, regardless which one it is?
    Last edited by CodesAway; 11-10-2009 at 11:44 PM.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  6. #6
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    Um, well "\n" is the only line break or separator that I'm familiar with. I just want each line to be read for each phrase. So if I have
    How are you?
    Como estas?

    "How are you?" should be read, put into phrases, then go to "Como estas?" and put it into phrases. So should I use
    scan.useDelimiter("\n") or scan.useDelimiter(System.getProperity("line.separa tor"))?

  7. #7
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    Hm well scan.useDelimiter("\n"); seems to work fine for what I need. getPhrases() is now working correctly. The program asks me how long the timer should be, but when I enter something in, the program ends so the JTextFields are still not showing up.

  8. #8
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    You might want to use a regex that matches ANY of the line separators. This way, no matter if it's "\n", "\r\n", or "\r", you are fine.

    Java Code:
    scan.useDelimiter("\r?\n|\r");
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  9. #9
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    Whenever I start the program, it seems as if the grabFocus() method is not working. I am unable to get my cursor on the translated (the right one) until after the program compares the two. This is the whole code now slightly updated -

    Java Code:
    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))) {
                        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();
        }
    
    }
    Another small problem is that when the JOptionPane is telling the user there is a new phrase, I want it pop-up or at least flash or something. As of now, I have no notification until I actually click on the GUI. Is there a way to fix these problems?

  10. #10
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    I noticed a BIG problem with your code, when you have the thread sleep, this means that thread doesn't respond (to any input). I bet this is what your problem is.

    I was trying to figure out why when I tried to type, nothing showed for several seconds - it's because the thread was asleep for that time. Because, after this time, the text I typed appeared in the box.


    BTW, the API, says to use
    Java Code:
    translated.requestFocusInWindow();
    instead of
    Java Code:
    translated.grabFocus();

    Also, you should clear the "translated" text after each phrase is done.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  11. #11
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    Is there a way to make the program pause, without using the sleep() method? That seems to be the only problem I have now.

  12. #12
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    I've never used Timers before, but it sounds like a Timer is what you need. I'm not sure the difference between swing timers and normal timers, but check out the "Java Timer Tutorial" for information.

    Sorry, I can't be much help on this topic. You might want to search for this, or start a new topic. I'm sure there are users that are more familiar with this who can help you better.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  13. #13
    Chasingxsuns is offline Member
    Join Date
    Jul 2009
    Posts
    56
    Rep Power
    0

    Default

    Okay instead of using Thread.sleep(5000), I placed these lines in go() -

    Java Code:
    //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();
    Then actionPerformed just checks and compares. At the end of actionPerformed, I put those lines again and cleared translated. Works fine now with the exception of JOptionPane not notifying as well as I liked, but I'm sure there is somewhere on the web to find an answer for that. Thanks for the help CodesAway.

  14. #14
    CodesAway's Avatar
    CodesAway is offline Senior Member
    Join Date
    Sep 2009
    Location
    Texas
    Posts
    238
    Rep Power
    5

    Default

    You're welcome, glad to help. And thank you, a learned a little more about threads and swing, my weak areas.
    CodesAway - codesaway.info
    writing tools that make writing code a little easier

  15. #15
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    It sounds like you really want to use a Swing Timer, but you will need to set repeats to false. Here's a very simple example:

    Java Code:
    import java.awt.event.*;
    import java.util.Random;
    
    import javax.swing.*;
    
    public class LanguageStudyB {
       private static final String[] PHRASES = {"The rain in spain", "Welease Wodewick!", "Make my day!", "Do you feel lucky, punk?", 
          "What we have here is a failure to communicate", "What is the air-speed velocity of the fully laden swallow?",
          "What's your favorite color?", "Frankly my dear, I don't give a damn!", "May the force be with you", 
          "Houston, we have a problem", "Show me the money!"};
       private JPanel mainPanel = new JPanel();
       private JTextField timeField = new JTextField("10", 5);
       private JTextArea textAreaDisplay = new JTextArea(15, 40);
       private JTextArea textAreaResponse = new JTextArea(15, 40);
       private JButton getPhraseBtn = new JButton("Get Phrase");
       private Random random = new Random();
       private String phrase = "";
    
       public LanguageStudyB() {
          JPanel timePanel = new JPanel();
          timePanel.add(new JLabel("Time Delay (in sec):"));
          timePanel.add(timeField);
          textAreaDisplay.setEditable(false);
          
          getPhraseBtn.addActionListener(new ActionListener() {
             
             public void actionPerformed(ActionEvent e) {
                phrase = PHRASES[random.nextInt(PHRASES.length)];
                textAreaDisplay.setText(phrase);
                getPhraseBtn.setEnabled(false);
                
                try {
                   int timerDelay = Integer.parseInt(timeField.getText());
                   Timer timer = new Timer(timerDelay * 1000, new TimerListener());
                   timer.setRepeats(false);
                   timer.start();
                }
                catch (NumberFormatException e1) {
                   timeField.setText("");
                   textAreaDisplay.setText("");
                   textAreaResponse.setText("");
                   getPhraseBtn.setEnabled(true);
                }
             }
          });
          
          mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.PAGE_AXIS));
          mainPanel.add(timePanel);
          mainPanel.add(new JScrollPane(textAreaDisplay));
          mainPanel.add(new JScrollPane(textAreaResponse));
          mainPanel.add(getPhraseBtn);
       }
    
       public JComponent getComponent() {
          return mainPanel;
       }
       
       private class TimerListener implements ActionListener {
          
          public void actionPerformed(ActionEvent e) {
             if (phrase.equalsIgnoreCase(textAreaResponse.getText())) {
                textAreaResponse.setText("Correct!  The phrases match!");
             } else {
                textAreaResponse.setText("Incorrect!  The phrases don't match!");
             }
             getPhraseBtn.setEnabled(true);
          }
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("LanguageStudyB");
          frame.getContentPane().add(new LanguageStudyB().getComponent());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }

Similar Threads

  1. Program Compiles but Buttons do not display
    By ljk8950 in forum AWT / Swing
    Replies: 8
    Last Post: 08-11-2008, 03:41 AM
  2. Display program
    By nhlfan in forum New To Java
    Replies: 2
    Last Post: 11-22-2007, 12:00 AM
  3. Swing program to display JVM information
    By satya007 in forum AWT / Swing
    Replies: 3
    Last Post: 11-13-2007, 09:59 AM
  4. My program doesnt display anything
    By Bojevnik in forum AWT / Swing
    Replies: 2
    Last Post: 10-19-2007, 02:50 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •