ActionListener和event.getSource()

时间:2015-10-20 19:59:31

标签: java

我在Java代码中遇到了一个问题。 每当我尝试在我的程序上使用我的按钮时它们都不起作用,我认为问题出在event.getSource()但是我找不到它。 这是我的完整代码:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*; 

public class Safe extends JFrame implements ActionListener{
    private JButton b1, b2, b3;
    private JTextField display;
    private JLabel displayLabel;
    private int[] pass = new int[5];
    private int hits = 0;

    public static void main(String[] args){
        Safe frame = new Safe();
        frame.setSize(250, 100);
        frame.createGUI();
        frame.setVisible(true);
    }

    private void createGUI(){
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        Container window = getContentPane();
        window.setLayout(new FlowLayout());

        b1 = new JButton("1");
        window.add(b1);
        b1.addActionListener(this);

        b2 = new JButton("2");
        window.add(b2);
        b2.addActionListener(this);

        b3 = new JButton("3");
        window.add(b3);
        b3.addActionListener(this);

        displayLabel = new JLabel("Enter 6 digit combination:");
        window.add(displayLabel);

        display = new JTextField(6);
        window.add(display);
    }

    public void actionPerformed(ActionEvent event){
        int i;
        int[] user = new int[5];
        if(hits == 0){
            pass[0] = 1;
            pass[1] = 1;
            pass[2] = 1;
            pass[3] = 1;
            pass[4] = 1;
            pass[5] = 2;
        }
        for(i=0;i<5;i++){
            if(event.getSource() == b1){
                display.setText("1");
                user[i] = 1;
            }
            else if(event.getSource() == b2){
                display.setText("2");
                user[i] = 2;
            }
            else if(event.getSource() == b3){
                display.setText("3");
                user[i] = 3;
            }
        }
        i = -1;
        do{
            i++;
            if(pass[i] != user[i]){
                JOptionPane.showMessageDialog(null,"Incorrect Code! Try Again!");
            }

            if(i == 5){
                JOptionPane.showMessageDialog(null,"Correct Code!");
            }
        }while(pass[i] == user[i]);
    }
}

收到错误

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 5
at Safe.actionPerformed(Safe.java:53)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)

1 个答案:

答案 0 :(得分:2)

int[] user = new int[5];
...
//pass[5] = 2;

Arrary索引是基于0的,所以索引5实际上是不存在的第6个条目。所以摆脱那句话。