Basically, what I have are 2 arrays. One array of JButton
s 26 long, one array of String
s with each letter of the alphabet, and a for loop to create a button for each letter of the alphabet and insert it into the JButton
array:
JButton[] buttons = new JButton[26];
String letters[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(letters[i]);
panel.add(buttons[i]);
}
What I want to do is create an event for all the buttons. Whenever a button is pressed, whatever letter it coincides with will be set as the value for a String
called guess.
So far I understand that I need to do something like this:
x.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
//Insert what I want to happen
}
});
My problem is with where I wrote x. I am not sure what to put there. I need this to work for all 26 buttons in the array...
Sorry if this seems obvious/simple. I am obviously new to java and I just don't understand how JButton
s work and how to do this.
Define an ActionListener like shown below.
ActionListener aListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event){
//find the actioncommand and do what is required.
}
};
Associate this ActionListener to every button.
for(int i = 0; i < buttons.length; i++){
buttons[i] = new JButton(letters[i]);
buttons[i].setActionCommand(letters[i]);
buttons[i].addActionListener(aListener);
panel.add(buttons[i]);
}
Just test the actionCommand which is a String value and compare it with a the letter, and do something.
x.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if (e.getActionCommand().equals("A")
// do something
else if (e.getActionCommand().equals("B")
// do soemthing
...
...
}
});
I prefer to use a switch though for cases like this.
public void actionPerformed(ActionEvent e){
String letter = e.getActionCommand();
switch(letter) {
case "A" : do something; break;
case "B" : do something; break;
case "C" : do something; break;
...
...
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.