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: Can't get JLabel to change text while program is running.

  1. #1
    Junior Member
    Join Date
    Feb 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Can't get JLabel to change text while program is running.

    I'm writing a program that lists a word taken randomly from an array of words and has a text field next to it. When the user types something in the text field and presses enter, it should perform an update that changes the word among some other tasks. However, when I run it, I can see that an action is registered as having been performed because I put in a println, but the JLable won't change its text.

    Here's the code:
    package com.jollex.TypingTest;
     
    import javax.swing.*;
    import java.util.Random;
    import java.awt.event.*;
    import java.io.*;
     
    public class Screen {
    	JFrame frame;
    	JPanel contentPane;
    	static JLabel word;
    	static JTextField ans;
    	static int num = 270;
    	static int[] numbers = new int[271];
    	static int wordsCorrect = 0;
    	static int wordsTotal = 0;
    	static boolean timerOn = false;
    	boolean gameDone = false;
    	static String[] words = new String[269];
     
    	public Screen() {
    		//Create and set up the frame
    		frame = new JFrame("Typing Test");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     
    		//Create a content pane
    		contentPane = new JPanel();
     
    		//Create and add label
    		word = new JLabel(newWord());
    		contentPane.add(word);
     
    		//Create and add text field
    		ans = new JTextField(20);
    		contentPane.add(ans);
     
    		//Creates action listener for text field and adds it
    		ActionListener enter = new ActionListener() {
    			@Override
    			public void actionPerformed(ActionEvent e) {
    				if (timerOn == true) update();
    				//Test to see if action listener works (remove later)
    				System.out.println("Action performed.");
    			}
    		};
    		ans.addActionListener(enter);
     
     
    		//Add content pane to frame
    		frame.setContentPane(contentPane);
     
    		//Size and then display the frame
    		frame.pack();
    		frame.setVisible(true);
     
    		//Start timer
    		timerOn = true;
    		timer.start();
    	}
     
    	//Creates a 60 second timer
    	ActionListener updater = new ActionListener() {
    		int count=0;
    		public void actionPerformed(ActionEvent time) {
    			if (count >= 60000) {
    				timerOn = false;
    				timer.stop();
    				gameDone = true;
    			}
    			count++;
    		}
    	};
    	Timer timer = new Timer(0, updater);
     
    	/**
    	 *Updates the display:
    	 *Checks the answer
    	 *Sets the label to a new word
    	 *Selects all text in the text field.
    	 */
    	public static void update() {
    		checkAns();
    		word.setText(newWord());
    		ans.selectAll();
    	}
     
    	//Checks if the answer is correct and adds points accordingly.
    	private static void checkAns() {
    		String word = getCurrentWord();
    		String word2 = null;
    		word2 = getAns();
    		if (word2.equals(word)) {
    			wordsCorrect += 1;
    			wordsTotal += 1;
    		} else {
    			wordsTotal += 1;
    		}
    	}
     
    	//Returns a new word from the words array.
    	public static String newWord() {
    		return words[randomInt()];
    	}
     
    	//Returns current word being displayed in the label.
    	public static String getCurrentWord() {
    		return words[num];
    	}
     
    	//Returns text from text field.
    	public static String getAns() {
    		String userAns = null;
    		userAns = ans.getText();
    		return userAns;
    	}
     
    	//Keeps an array of numbers from 0-269. Returns a random number and removes that number after it's been used.
    	public static int randomInt() {
    		for (int i = 0; i < 271; i++) {
    			numbers[i] = i;
    		}
    		Random generator = new Random();
    		while (numbers[num] == 270) {
    			num = generator.nextInt(270);
    		}
    		numbers[num] = 270;
    		return num;
    	}
     
    	//Loads words from words.txt to a string array called words.
    	private static void loadWords() {
    		File wordFile = new File("words.txt");
    		FileReader in;
    		BufferedReader readFile;
    		String nextWord;
     
    		try {
    			in = new FileReader(wordFile);
    			readFile = new BufferedReader(in);
    			int i = 0;
    			while ((nextWord = readFile.readLine()) != null && i < words.length) {
    				words[i] = nextWord;
    				i++;
    			}
    			readFile.close();
    			in.close();
    		} catch (FileNotFoundException e) {
    			System.out.println("File does not exist or could not be found.");
    			System.err.println("FileNotFoundException: " + e.getMessage());
    		} catch (IOException e) {
    			System.out.println("Problem reading file.");
    			System.err.println("IOException: " + e.getMessage());
    		}
    	}
     
    	//Creates and shows the GUI
    	public static void runGUI() {
    		JFrame.setDefaultLookAndFeelDecorated(true);
     
    		@SuppressWarnings("unused")
    		Screen screen = new Screen();
    	}
     
    	public static void main(String[] args) {
    		loadWords();
    		javax.swing.SwingUtilities.invokeLater(new Runnable() {
    			public void run() {
    				runGUI();
    			}
    		});
    	}
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Can't get JLabel to change text while program is running.

    You need to add lots more println statements to see what the code is doing. Print out the values of variables as they are used and changed.
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Feb 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't get JLabel to change text while program is running.

    Quote Originally Posted by Norm View Post
    You need to add lots more println statements to see what the code is doing. Print out the values of variables as they are used and changed.
    Thanks for the advice, by placing some more println statements around, I figured out that it the problem isn't that the JLabel isn't updating, but I think the issue is with the randomInt() method because it is returning the same word every time, instead of giving a new random number. I'm not sure how to fix this.

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Can't get JLabel to change text while program is running.

    randomInt() method because it is returning the same word
    How does randomInt() generate the number it returns?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Feb 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't get JLabel to change text while program is running.

    It has it's own method that creates a random number generator using the java.util.Random class and then uses the nextInt() method to get the next random integer.

    Here's the method from my code:
    	public static int randomInt() {
    		for (int i = 0; i < 271; i++) numbers[i] = i;
    		Random generator = new Random();
    		while (numbers[num] == 270) num = generator.nextInt(270);
    		numbers[num] = 270;
    		return num;
    	}

    EDIT:
    I did some reading and found out I shouldn't be creating the Random generator inside my method, so I moved it outside the method, into just the class and now I have just the generator.nextInt(270) portion in the randomInt() method.

    Like so:
    	private Random generator = new Random();
    	public int randomInt() {
    		for (int i = 0; i < 271; i++) numbers[i] = i;
    		while (numbers[num] == 270) num = generator.nextInt(270);
    		numbers[num] = 270;
    		return num;
    	}

    However, the random generator is still returning the same integer every time I run randomInt() by causing an action event.

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Can't get JLabel to change text while program is running.

    Try debugging the method by adding some printlns to see what values the variables in the method have.
    The printout should show you what is happening.


    The code has some hard coded magic numbers (270 and 271) that should not be coded that way.
    The values should be defined as variables or obtained from other sources like the length of an array.
    If you don't understand my answer, don't ignore it, ask a question.

  7. #7
    Junior Member
    Join Date
    Feb 2013
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Can't get JLabel to change text while program is running.

    I figured it out, the for loop in my randomInt() method was loading the numbers array with the integers from 0-270 every time I called the randomInt() method, so I moved it out into it's own method called loadRandom() which is only run once, before the GUI is loaded. Thank you for the help, adding the println statements in really helped me and I will keep that in mind the next time problems arise.

Similar Threads

  1. Using a JSlider to change the red contrast of an image on a jLabel
    By Bruz69er in forum What's Wrong With My Code?
    Replies: 0
    Last Post: November 22nd, 2012, 01:40 AM
  2. passing value and setting it to jlabel text
    By Ibanez1408 in forum What's Wrong With My Code?
    Replies: 1
    Last Post: September 19th, 2012, 07:10 AM
  3. Loop through JLabel and change JLabel
    By JoeBrown in forum What's Wrong With My Code?
    Replies: 2
    Last Post: April 11th, 2012, 12:52 PM
  4. Change a JLabel value that is in another class?
    By jm24 in forum AWT / Java Swing
    Replies: 3
    Last Post: February 17th, 2012, 08:13 PM
  5. adding text to JLabel during actionPerformed
    By that_guy in forum AWT / Java Swing
    Replies: 1
    Last Post: February 12th, 2012, 04:08 PM

Tags for this Thread