2017-09-28 2 views
0

Pour une raison quelconque, lorsque je clique sur le bouton GO, MainScreenHandler passe deux fois en boucle. Notez que cela ne se produit pas au premier clic, mais se produit lors des clics suivants.Action Listener bouclé plusieurs fois en un clic

Je crois que le problème est dû au fait que je change le programme d'écoute d'action en ChoiceHandler après le premier clic et que je le change ensuite en MainScreenHandler.

Je ne sais vraiment pas pourquoi. Je suis nouveau à Java et essaye d'écrire un jeu d'aventure avec une interface graphique. D'autres conseils seraient appréciés aussi.

Voici la classe MainGameScreen.

package textAdvTwo; 

import java.awt.Color; 
import java.awt.Container; 
import java.awt.Font; 
import java.awt.GridLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.awt.event.ItemEvent; 
import java.util.ArrayList; 

import javax.swing.ImageIcon; 
import javax.swing.JButton; 
import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.JTextArea; 

public class MainGameScreen { 
    JFrame window; 
    Container con; 
    ImageIcon badge; 
    JPanel titleNamePanel, startButtonPanel, mainTextPanel, choiceButtonPanel, 
      infoPanel, badgeLabelPanel, warningTextPanel; 
    JLabel titleNameLabel, locationLabel, locationLabelNumber, inventoryLabel, 
      inventoryLabelName, badgeLabel, warningLabel; 
    Font titleFont = new Font("Times New Roman", Font.PLAIN, 40); 
    Font normalFont = new Font("Times New Roman", Font.PLAIN, 18); 
    Font largerFont = new Font("Times New Roman", Font.PLAIN, 24); 
    Font mainTextFont = new Font("Times New Roman", Font.PLAIN, 28); 
    JButton startButton, goButton, lookButton, searchButton, inventoryButton, 
      giveButton, talkButton, dropButton, unknownButton; 
    JTextArea mainTextArea, warningTextArea; 
    int playerHP, monsterHP, silverRing; 
    String weapon, position; 
    GameFlow gameFlow = new GameFlow(); 
    JButton[] buttons = new JButton[8]; 

    TitleScreenHandler tsHandler = new TitleScreenHandler(); 
    MainGameScreenHandler choiceHandler = new MainGameScreenHandler(); 
    ItemChoiceHandler itemChoiceHandler = new ItemChoiceHandler(); 

    public MainGameScreen() { 

     window = new JFrame(); 
     window.setSize(800, 600); 
     window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     window.getContentPane().setBackground(Color.black); 
     window.setLayout(null); 
     con = window.getContentPane(); 

     titleNamePanel = new JPanel(); 
     titleNamePanel.setBounds(100, 450, 600, 150); 
     titleNamePanel.setBackground(Color.black); 
     titleNameLabel = new JLabel("A day in the life of Rafa Benitez..."); 
     titleNameLabel.setForeground(Color.white); 
     titleNameLabel.setFont(titleFont); 

     badge = new ImageIcon(getClass().getResource("badge.jpg")); 
     badgeLabel = new JLabel(badge); 

     badgeLabelPanel = new JPanel(); 
     badgeLabelPanel.setBounds(200, 0, 400, 400); 
     badgeLabelPanel.setBackground(Color.WHITE); 
     badgeLabelPanel.add(badgeLabel); 

     startButtonPanel = new JPanel(); 
     startButtonPanel.setBounds(300, 400, 200, 100); 
     startButtonPanel.setBackground(Color.black); 

     startButton = new JButton("START"); 
     startButton.addActionListener(tsHandler); 
     startButton.setForeground(Color.black); 
     startButton.setFont(normalFont); 

     startButton.setFocusPainted(false); 

     titleNamePanel.add(titleNameLabel); 
     startButtonPanel.add(startButton); 

     con.add(badgeLabelPanel); 
     con.add(titleNamePanel); 
     con.add(startButtonPanel); 
     window.setVisible(true); 

    } 

    public void createGameScreen() { 

     titleNamePanel.setVisible(false); 
     startButtonPanel.setVisible(false); 
     badgeLabelPanel.setVisible(false); 

     mainTextPanel = new JPanel(); 
     mainTextPanel.setBounds(100, 130, 600, 200); 
     mainTextPanel.setBackground(Color.black); 
     con.add(mainTextPanel); 

     warningTextPanel = new JPanel(); 
     warningTextPanel.setBounds(300, 25, 500, 50); 
     warningTextPanel.setBackground(Color.black); 
     con.add(warningTextPanel); 

     mainTextArea = new JTextArea(); 
     mainTextArea.setBounds(100, 100, 600, 200); 
     mainTextArea.setBackground(Color.black); 
     mainTextArea.setForeground(Color.white); 
     mainTextArea.setFont(mainTextFont); 
     mainTextArea.setLineWrap(true); 
     mainTextArea.setText(mainTextDesc(gameFlow.locations, gameFlow.rafa, 
       gameFlow.characs)); 
     mainTextPanel.add(mainTextArea); 

     warningTextArea = new JTextArea(); 
     warningTextArea.setBounds(300, 25, 500, 50); 
     warningTextArea.setBackground(Color.black); 
     warningTextArea.setForeground(Color.red); 
     warningTextArea.setFont(normalFont); 
     warningTextArea.setLineWrap(true); 
     warningTextPanel.add(warningTextArea); 

     choiceButtonPanel = new JPanel(); 
     choiceButtonPanel.setBounds(250, 400, 300, 150); 
     choiceButtonPanel.setBackground(Color.white); 
     choiceButtonPanel.setLayout(new GridLayout(4, 2)); 
     con.add(choiceButtonPanel); 

     goButton = new JButton(); 
     goButton.setText("GO"); 
     goButton.setForeground(Color.black); 
     goButton.setFont(normalFont); 
     goButton.setFocusPainted(false); 
     goButton.addActionListener(choiceHandler); 
     goButton.setActionCommand("go"); 
     buttons[0] = goButton; 
     choiceButtonPanel.add(goButton); 
     lookButton = new JButton(); 
     lookButton.setText("LOOK"); 
     lookButton.setForeground(Color.black); 
     lookButton.setFont(normalFont); 
     lookButton.setFocusPainted(false); 
     lookButton.addActionListener(choiceHandler); 
     lookButton.setActionCommand("look"); 
     buttons[1] = lookButton; 
     choiceButtonPanel.add(lookButton); 
     searchButton = new JButton(); 
     searchButton.setText("SEARCH"); 
     searchButton.setForeground(Color.black); 
     searchButton.setFont(normalFont); 
     searchButton.setFocusPainted(false); 
     searchButton.addActionListener(choiceHandler); 
     searchButton.setActionCommand("search"); 
     buttons[2] = searchButton; 
     choiceButtonPanel.add(searchButton); 
     inventoryButton = new JButton(); 
     inventoryButton.setText("INVENTORY"); 
     inventoryButton.setForeground(Color.black); 
     inventoryButton.setFont(normalFont); 
     inventoryButton.setFocusPainted(false); 
     inventoryButton.addActionListener(choiceHandler); 
     inventoryButton.setActionCommand("inventory"); 
     buttons[3] = inventoryButton; 
     choiceButtonPanel.add(inventoryButton); 
     giveButton = new JButton(); 
     giveButton.setText("GIVE"); 
     giveButton.setForeground(Color.black); 
     giveButton.setFont(normalFont); 
     giveButton.setFocusPainted(false); 
     giveButton.addActionListener(choiceHandler); 
     giveButton.setActionCommand("give"); 
     buttons[4] = giveButton; 
     choiceButtonPanel.add(giveButton); 
     talkButton = new JButton(); 
     talkButton.setText("TALK"); 
     talkButton.setForeground(Color.black); 
     talkButton.setFont(normalFont); 
     talkButton.setFocusPainted(false); 
     talkButton.addActionListener(choiceHandler); 
     talkButton.setActionCommand("talk"); 
     buttons[5] = talkButton; 
     choiceButtonPanel.add(talkButton); 
     dropButton = new JButton(); 
     dropButton.setText("DROP"); 
     dropButton.setForeground(Color.black); 
     dropButton.setFont(normalFont); 
     dropButton.setFocusPainted(false); 
     dropButton.addActionListener(choiceHandler); 
     dropButton.setActionCommand("drop"); 
     buttons[6] = dropButton; 
     choiceButtonPanel.add(dropButton); 
     unknownButton = new JButton(); 
     unknownButton.setText("UNKNOWN"); 
     unknownButton.setForeground(Color.black); 
     unknownButton.setFont(normalFont); 
     unknownButton.setFocusPainted(false); 
     unknownButton.addActionListener(choiceHandler); 
     unknownButton.setActionCommand("unknown"); 
     buttons[7] = unknownButton; 
     choiceButtonPanel.add(unknownButton); 

     infoPanel = new JPanel(); 
     infoPanel.setBounds(100, 15, 350, 90); 
     infoPanel.setBackground(Color.black); 
     infoPanel.setLayout(new GridLayout(1, 4)); 
     con.add(infoPanel); 
     locationLabel = new JLabel("Location:"); 
     locationLabel.setFont(normalFont); 
     locationLabel.setForeground(Color.white); 
     infoPanel.add(locationLabel); 
     locationLabelNumber = new JLabel(); 
     locationLabelNumber.setFont(largerFont); 
     locationLabelNumber.setForeground(Color.blue); 
     locationLabelNumber.setText(getLocation(gameFlow.locations, 
       gameFlow.rafa)); 
     infoPanel.add(locationLabelNumber); 


    } 
    public void refreshMainScreen(){ 
     goButton.setText("GO"); 
     goButton.setActionCommand("go"); 
     goButton.addActionListener(choiceHandler); 
     lookButton.setText("LOOK"); 
     lookButton.setActionCommand("look"); 
     lookButton.addActionListener(choiceHandler); 
     searchButton.setText("SEARCH"); 
     searchButton.setActionCommand("search"); 
     searchButton.addActionListener(choiceHandler); 
     inventoryButton.setText("INVENTORY"); 
     inventoryButton.setActionCommand("inventory"); 
     inventoryButton.addActionListener(choiceHandler); 
     giveButton.setText("GIVE"); 
     giveButton.setActionCommand("give"); 
     giveButton.addActionListener(choiceHandler); 
     talkButton.setText("TALK"); 
     talkButton.setActionCommand("talk"); 
     talkButton.addActionListener(choiceHandler); 
     dropButton.setText("DROP"); 
     dropButton.setActionCommand("drop"); 
     dropButton.addActionListener(choiceHandler); 
     unknownButton.setText("UNKNOWN"); 
     unknownButton.setActionCommand("unknown"); 
     unknownButton.addActionListener(choiceHandler); 
     mainTextArea.setText(mainTextDesc(gameFlow.locations, gameFlow.rafa, 
       gameFlow.characs)); 
     locationLabelNumber.setText(getLocation(gameFlow.locations, 
       gameFlow.rafa)); 
     /*inventoryLabelName.setText(inventoryLabel(gameFlow.rafa));*/ 
    } 

    public class TitleScreenHandler implements ActionListener { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      // TODO Auto-generated method stub 
      createGameScreen(); 
     } 

    } 
    public class ItemChoiceHandler implements ActionListener{ 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      // TODO Auto-generated method stub 
      System.out.println("itemAL"); 
      String choice = e.getActionCommand(); 
      gameFlow.rafa.inventory.get(Integer.parseInt(choice)).setX(gameFlow.rafa.getX()); 
      gameFlow.rafa.inventory.get(Integer.parseInt(choice)).setY(gameFlow.rafa.getY()); 
      gameFlow.items.add(gameFlow.rafa.inventory.get(Integer.parseInt(choice))); 
      gameFlow.rafa.inventory.remove(Integer.parseInt(choice)); 
      for(int i = 0; i<gameFlow.rafa.inventory.size(); i++){ 
       buttons[i].removeActionListener(itemChoiceHandler); 
       } 

      refreshMainScreen(); 
     } 

    } 

    public class MainGameScreenHandler implements ActionListener { 

     @Override 
     public void actionPerformed(ActionEvent e) { 
      // TODO Auto-generated method stub 
      String choice = e.getActionCommand(); 

      if (choice.equals("go")) { 
       go(); 
       System.out.println("go"); 
      } else if (choice.equals("look")) { 
       refreshMainScreen(); 
      } else if (choice.equals("search")) { 
       search(); 
      } else if (choice.equals("inventory")) { 
       inventory(gameFlow.rafa); 
      } else if (choice.equals("give")) { 

      } else if (choice.equals("talk")) { 
       System.out.println("talk"); 
      } else if (choice.equals("drop")) { 
       drop(gameFlow.rafa); 
      } else if (choice.equals("unknown")) { 
       System.out.println("unknown"); 
      } else if (choice.equals("north")){ 
       if(gameFlow.rafa.x > 0){ 
        gameFlow.rafa.moveNorth(); 
        System.out.println("north"); 
        warningTextArea.setText(""); 
       } 
       else{ 
        warningTextArea.setText("You can't move that way."); 
       } 
       refreshMainScreen(); 
      } else if (choice.equals("east")){ 
       if(gameFlow.rafa.y < 2){ 
        gameFlow.rafa.moveEast(); 
        warningTextArea.setText(""); 
       } 
       else{ 
        warningTextArea.setText("You can't move that way."); 
       } 
       refreshMainScreen(); 
      } else if (choice.equals("west")){ 
       if(gameFlow.rafa.y > 0){ 
        gameFlow.rafa.moveWest(); 
        warningTextArea.setText(""); 
       } 
       else{ 
        warningTextArea.setText("You can't move that way."); 
       } 
       refreshMainScreen(); 
      } else if (choice.equals("south")){ 
       if(gameFlow.rafa.x < 2){ 
        gameFlow.rafa.moveSouth(); 
        System.out.println("south"); 
        warningTextArea.setText(""); 
       } 
       else{ 
        warningTextArea.setText("You can't move that way."); 
       } 
       refreshMainScreen(); 
      } 
      } 


     } 

    public void drop(Rafa rafa){ 
     String buttonNames[] = {"0","1","2","3","4","5","6","7"}; 
     mainTextArea.setText("What do you want to drop?"); 
     if(rafa.inventory.size() == 0){ 
      mainTextArea.setText("You have nothing to drop!"); 
     } 
     else{ 
      for(int i = 0; i<rafa.inventory.size(); i++){ 
       buttons[i].setText(rafa.inventory.get(i).getName());   
       buttons[i].setActionCommand(buttonNames[i]); 
       buttons[i].removeActionListener(choiceHandler); 
       buttons[i].addActionListener(itemChoiceHandler); 
       } 
      for(int j = rafa.inventory.size(); j<8; j++){ 
        buttons[j].setText(""); 
       } 
      } 
     } 



    public void search() { 
     Items itemFound = searchRoom(gameFlow.rafa, gameFlow.items); 
     if (itemFound != null) { 
      gameFlow.rafa.inventory.add(itemFound); 
      gameFlow.items.remove(itemFound); 
      mainTextArea.setText(itemFound.firstTimeDesc); 
     } else { 
      mainTextArea.setText("Your search reveals nothing new."); 
     } 
    } 

    public Items searchRoom(Rafa rafa, ArrayList<Items> items) { 
     Items item = null; 
     for (Items it : items) { 
      if (it.getX() == rafa.getX() && it.getY() == rafa.getY()) { 
       item = it; 
      } 
     } 
     return item; 
    } 

    public String getLocation(Locations[][] locations, Rafa rafa) { 
     return locations[rafa.getX()][rafa.getY()].getName(); 
    } 

    public String mainTextDesc(Locations[][] locations, Rafa rafa, 
      ArrayList<NonPlayingCharac> characs) { 
     String desc = ""; 
     if (whoIsInRoom(rafa, characs).size() == 0) { 
      desc += locations[rafa.getX()][rafa.getY()].getDesc(); 
     } else { 
      String inRoom = ""; 
      for (NonPlayingCharac person : whoIsInRoom(rafa, characs)) { 
       if (person == null) { 
        continue; 
       } else { 
        inRoom += person.getFullName() + "\n"; 
       } 
       desc += locations[rafa.getX()][rafa.getY()].getDesc() 
         + "\n\nIn the room you also see\n" + inRoom; 
      } 
     } 
     return desc; 
    } 

    public ArrayList<NonPlayingCharac> whoIsInRoom(Rafa rafa, 
      ArrayList<NonPlayingCharac> characs) { 
     ArrayList<NonPlayingCharac> inRoom = new ArrayList<NonPlayingCharac>(); 
     for (NonPlayingCharac person : characs) { 

      if (person.getX() == rafa.getX() && person.getY() == rafa.getY()) { 
       inRoom.add(person); 
      } 
     } 
     return inRoom; 
    } 

    public void inventory(Rafa rafa) { 
     String invent = "You are carrying:\n"; 
     if (rafa.inventory.size() != 0) { 
      for (Items item : rafa.inventory) { 
       invent += item.name + ", " + item.description + "\n"; 
      } 
     } else { 
      invent += "nothing."; 
     } 
     mainTextArea.setText(invent); 
    } 

    public String inventoryLabel(Rafa rafa) { 
     String inventory = ""; 
     if (rafa.inventory.size() != 0) { 
      for (Items item : rafa.inventory) { 
       inventory += "\n" + item.name ; 
      } 
     } else { 
      inventory = "Nothing."; 
     } 
     return inventory; 
    } 

    public void go() { 
     mainTextArea.setText("Which direction?"); 
     goButton.setText("NORTH"); 
     goButton.setActionCommand("north"); 
     searchButton.setText("EAST"); 
     searchButton.setActionCommand("east"); 
     giveButton.setText("WEST"); 
     giveButton.setActionCommand("west"); 
     dropButton.setText("SOUTH"); 
     dropButton.setActionCommand("south"); 
     lookButton.setText(""); 
     inventoryButton.setText(""); 
     talkButton.setText(""); 
     unknownButton.setText(""); 
    } 
} 

Répondre

0

Vous faites beaucoup d'ajout et de suppression d'écouteurs d'actions, ce qui peut très facilement mener à des erreurs comme celle-ci. Les écouteurs sont stockés dans une liste, il n'y a donc aucune vérification de sécurité pour ajouter des doublons, ou s'assurer qu'il n'y a qu'un seul écouteur assigné au bouton.

Dans ce cas, après une brève lecture de votre code, il apparaît que le bouton "GO" finit par se retrouver avec deux écouteurs d'action qui lui sont assignés. Cela signifie que la première fois, c'est bien, mais que le code est exécuté, ce qui ajoute un autre écouteur. La prochaine fois que vous appuyez sur le bouton, les deux écouteurs tirent.

+0

Merci pour vos commentaires. Je pensais que je supprimais les auditeurs d'action correctement, mais je suppose que non. Je vais essayer de créer un nouvel écran avec de nouveaux boutons lorsque l'utilisateur doit faire un second choix (c'est-à-dire GO puis DIRECTION) – stevo78