I have written two methods that take and return a string. One converts from English to Pig Latin and vice versa. I have two JTextFields (one English and the other Piglatin- for user input). Likewise, two JButtons: “To English” and “To Pig Latin”. I am confused how to use action listeners. It looks like it is possible to just have one ActionListener execute everything you want “on-click”, however I am confused about how it knows which button you pushed. I instinctively want to make two ActionListeners for each button, whereby when the button is clicked the appropriate code will be executed.
Could someone please show and/or explain to me how this all works?
Summary of how I understand everything so far:
- Type English words into JTextField
- Click “To Pig Latin” button
- ActionListener somehow knows the “To Pig Latin” button is clicked and executes the toPigLatin() method with the JTextField text as a parameter. (Assuming JTextField input is automatically considered a String type, really have not got that far yet).
- The String returned from that method is output to the Pig Latin JTextField for user to see.
Thanks everyone!
I found what I was looking for. Sorry I posted it on the wrong Forum and thanks for migrating it over here where it belongs…I meant to post it here! 🙂 For anyone trying to figure out how to make it so each button executes a certain block of code when clicked use the following: [ActionEvent].getActionCommand().equals(“[Name of Button]”)
Here’s my final solution if anyone is interested:
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("To Pig Latin")){
String english = English.getText();
PigLatin.setText(englishToPigLatin(english));
}
if (e.getActionCommand().equals("To English")){
String piglatin = PigLatin.getText();
English.setText(pigLatinToEnglish(piglatin));
}
String piggyCount = Integer.toString(pigCount);
countP.setText("Number of Successful Word Translations: English: "+piggyCount+" ");
String englishyCount = Integer.toString(englishCount);
countE.setText(String.format("Pig-Latin: "+englishyCount));
}
Thanks again everyone who tried to help me out!
There’s a good tutorial on ActionListeners here. The easiest way to use the same listener for two buttons is to call
e.getActionCommand()on theActionEventpassed to theactionPerformedfunction. That will return a string with the label of the button, which you can then use in anifstatement to perform the appropriate action.