Fetch text from TextField for use in an ActionEvent
Hi, I'm wiriting a small Java Hangman game and have run into a problem. I have a TextField that I'm using as a user input to guess a letter, however, I was having difficulty fetching the contents of the TextField for use in the ActionEvent. I managed to work out a quick and messy solution, but was wondering if there is a better way to do it? I have a feeling I'm doing something horribly wrong.
The inputLetter variable is the TextField that the actionListener is set to.
Java Code:
Code:
public Hangman()
{
Label welcome;
TextField guessWord;
TextField inputLetter;
setLayout(new FlowLayout());
setSize(400,400);
setTitle("Hangman!");
welcome = new Label("Welcome to hangman. Enter a letter to begin guessing!");
inputLetter = new TextField(1);
guessWord = new TextField(30);
guessWord.setEditable(false);
getContentPane().add(welcome);
getContentPane().add(guessWord);
getContentPane().add(inputLetter);
//Sample word array [replace with words read in from text file?]
String[] wordArray = {"excellent", "mindblowing","wonderful", "java", "program"};
//Choose random word
String thisWord = chooseRand.choose(wordArray);
System.out.println(thisWord);
String secretWord = thisWord;
char[] secretWordArray; //Create empty array to hold characters
secretWordArray = secretWord.toCharArray(); //convert secretWord String to array of characters
for(int i=0; i<secretWordArray.length; i++) {
/*
* This code runs through secretWordArray and replaces each
* character with underscores to represent
* missing or hidden letters
*/
secretWordArray[i] = '_';
System.out.println(secretWordArray);
}
secretWord = new String(secretWordArray);
guessWord.setText(secretWord);
/*
* secretWord is now a string of underscores
* thisWord is still the original word
*/
setDefaultCloseOperation(EXIT_ON_CLOSE);
inputLetter.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent event)
{
//Following code fetches the user input.
//VERY unhappy with this code!!
Object inputLetter = event.getSource();
String testLetter = inputLetter.toString();
char testChar = testLetter.charAt(48); //48 is the index of the string where the character is held
}
Any help would be greatly appreciated.
Thanks! Oh, and first post :)
EDIT: I don't know why, but lines 38 to 42 are commented out on this site. They shouldn't be!
Re: Fetch text from TextField for use in an ActionEvent
You'll need to make the TextField an attribute of the Hangman class so you can refer to it in the actionPerformed method.
Of course you could simply make the TextField final and instead of implementing ActionListener in the hangman class use an anonymous inner class:
Code:
inputLetter.addActionListener( new ActionListener() {
... implement methods here ...
});