动作侦听器一次循环多次

时间:2017-09-28 00:52:59

标签: java actionlistener

由于某种原因,当我单击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("");
    }
}

1 个答案:

答案 0 :(得分:0)

您正在做很多添加和删除动作侦听器,这很容易导致诸如此类的错误。侦听器存储在一个列表中,因此没有用于添加重复项的安全检查,或者确保只有一个侦听器分配给该按钮。

在这种情况下,从您的代码的简要阅读中可以看出&#34; GO&#34;按钮最终会分配给它的两个动作侦听器。这意味着它第一次没问题,但随后运行的代码会添加另一个监听器。下次按下按钮时,两个听众都会开火。