Reputation: 35
I'd like to have multiple ActionListener
's in my class. I'm making a simple game for a project that has 3 different levels, and a certain amount of buttons in each level.
After each level a new element or component is added. My first level has 25 buttons that when one is pushed they'll emit a random outcome which adds to your score. All these buttons do the same thing so I decided to use an ActionListener
instead of having to write out 10 if
statements per button. Problem being I want to do that with my second level but the class already has a defined action performed.
Is there any possible way to have more than one ActionListener
in the same class?
Here is my ActionPerformed
method:
public void actionPerformed(ActionEvent e) {
JButton source = (JButton)e.getSource();
Random RG = new Random();
level_1_random_block = (RG.nextInt(6));
frame2.setVisible(false);
if (level_1_random_block == 0){
source.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\oreDiamond.png"));
score += 100;
initialize_score();
}
if (level_1_random_block == 1){
source.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\oreGold.png"));
score += 25;
initialize_score();
}
if (level_1_random_block == 2){
source.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\oreGold.png"));
score += 25;
initialize_score();
}
if (level_1_random_block == 3){
source.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\oreIron.png"));
score += 5;
initialize_score();
}
if (level_1_random_block == 4){
source.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\oreIron.png"));
score += 5;
initialize_score();
}
if (level_1_random_block == 5){
source.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\creeper.png"));
score -= 30;
initialize_score();
try {
Clip clip = AudioSystem.getClip();
clip.open(AudioSystem.getAudioInputStream(new File("C:\\Users\\Liam\\Desktop\\BOMB GAME\\creeper_sound.wav")));
clip.start();
}
catch (Exception exc){
}
}
if (level_1_random_block == 6){
source.setIcon(new ImageIcon("C:\\Users\\Liam\\Desktop\\BOMB GAME\\creeper.png"));
score -= 30;
initialize_score();
}
source.removeActionListener((ActionListener) this);
level_1_move_on = true;
continue_game();
}
public void EventHandler(int level_1_random_block) {
this.level_1_random_block = level_1_random_block;
}
Upvotes: 0
Views: 1653
Reputation: 648
You can do an Inner Class:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){ */Code goes here*/
}
})
(save the actionListener in a variable and set it for many buttons)
Do this multiple times for different buttons and you have multipleActionListeners.
You can also set action commands.
button.setActionCommad("lvl1");
In your actionPerformed(ActionEvent e)
you can check with if:
if(e.getActionCommand.equals("lvl1")) { /*code*/ }
Upvotes: 1