2017-09-28 1 views
0

어떤 이유로 GO (진행) 버튼을 클릭하면 MainScreenHandler가 두 번 반복됩니다. 첫 번째 클릭에는 발생하지 않지만 후속 클릭에는 발생합니다.한 번의 클릭으로 여러 번 반복되는 동작 수신기

첫 번째 클릭 후 액션 수신기를 ChoiceHandler로 변경 한 다음 MainScreenHandler로 다시 변경하기 때문에 문제가 있다고 생각합니다.

나는 이것이 왜 있는지 전혀 모른다.

저는 Java를 처음 사용하고 GUI로 모험 게임을 작성하려고합니다. 다른 팁도 감상 할 수 있습니다.

다음은 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(""); 
    } 
} 

답변

0

액션 리스너를 추가하거나 제거하면 많은 실수를 유발할 수 있습니다. 리스너는 목록에 저장되므로 중복 추가에 대한 안전성 검사가 없거나 버튼에 할당 된 리스너가 하나만 있는지 확인해야합니다.

이 경우 코드를 열어 보니 "GO"버튼이 결국 두 개의 액션 리스너로 할당됩니다. 처음에는 괜찮 았지만 다른 리스너를 추가하는 코드가 실행되었습니다. 다음에 버튼을 누르면 두 청취자가 모두 소리를냅니다.

+0

의견에 감사드립니다. 나는 액션 리스너를 올바르게 제거하고 있다고 생각했지만 그렇지 않다고 생각한다. 사용자가 두 번째 선택을해야하는 경우 새 버튼으로 새 화면을 만들려고 시도합니다 (예 : GO, DIRECTION). – stevo78

관련 문제