2013-10-26 24 views
0

我想在我的課堂上有多個ActionListener。我爲一個有3個不同級別的項目製作了一個簡單的遊戲,並且每個級別都有一定數量的按鈕。一個類中的多個ActionListeners

在每個級別添加新元素或組件後。我的第一關有25個按鈕,當他們被推動時,他們會發出一個隨機結果,增加你的分數。所有這些按鈕做同樣的事情,所以我決定使用ActionListener,而不必寫每個按鈕10 if語句。問題是我想用我的第二級來做到這一點,但是班上已經有了一個定義好的動作。

是否有任何可能的方法在同一個班級中擁有多個ActionListener

這裏是我的ActionPerformed方法:

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;  
} 
+2

也許你想使用[Strategy設計模式(http://en.wikipedia.org/wiki/Strategy_design_pattern),允許一個ActionListener根據程序的狀態有不同的操作。 –

回答

1

你可以做一個內部類:

button.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){ */Code goes here*/ } }) (保存ActionListener的一個變量,並設置它的按鈕)

做到這一點多次爲不同的按鈕,你有multipleActionListeners。

您也可以設置動作命令。 button.setActionCommad("lvl1");

在你actionPerformed(ActionEvent e)你可以,如果檢查: if(e.getActionCommand.equals("lvl1")) { /*code*/ }

+0

你是什麼意思與解決? getActionCommand使用setActionCommand返回之前爲組件設置的字符串。 – Geosearchef