在数组中为菜单创建对象

时间:2014-04-12 22:02:53

标签: java arrays swing object jbutton

我正在尝试创建一个注册菜单,但是我无法在可访问的数组中创建对象。 超类构造函数:

Login(String fn, String ln, String acc, String by, String pw){
    firstName = fn;
    lastName = ln;
    account = acc;
    birthYear = by;
    password = pw;
}

在超级类中,我创建了一个类型为Login的数组。在子类Register中,我正在尝试在数组中创建对象。我的注册菜单有几个要填写的字段。我希望在字段为空且密码字段不匹配时弹出错误消息。

JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        boolean match = false;
        while (match == false){
        if (textField_4.getText().equals(textField_5.getText())){
        try{
            for (int i = count; i<= list.length;i++){
            list[i] = new Login(textField.getText(),textField_1.getText(),textField_2.getText(),textField_3.getText(),textField_4.getText());
            count++;
            match = true;
            }}
            catch (Exception e){
                JOptionPane.showMessageDialog(null, "Fields are empty", "Error", JOptionPane.INFORMATION_MESSAGE);
                System.out.println(e);
                break;
            }
        }
        else
            match = false;
            JOptionPane.showMessageDialog(null, "Password fields do not match!", "Error", JOptionPane.INFORMATION_MESSAGE);
            break;
        }
    }
});

我已经让密码不匹配功能正常工作但是当我尝试输入所有字段并创建对象时,我当前得到ArrayIndexOutOfBounds。我该如何解决这个问题?提前谢谢。

1 个答案:

答案 0 :(得分:0)

罪魁祸首很可能就是这两行

    for (int i = count; i<= list.length;i++){
    list[i] = ...

尝试访问&#34; 列表[list.length] &#34;会给你一个 ArrayIndexOutOfBounds ,因为indeces从0开始,所以 list 的最后一个索引是 list.length-1 ; < / p>

更改为&#34; i&lt; = list.length &#34;到&#34; i&lt; list.length &#34;