图像数组在下拉菜单中超出范围

时间:2015-08-20 22:19:01

标签: java arrays eclipse swing user-interface

我正在使用JCombo框进行基本项目,当图像更改框中选择了某些内容时。窗口和图像显示,但是当我从JCombo框中选择第二个图像时,我得到一个数组越界错误。请看一下:

<div id="imgfull">

<img src="http://thumbs.dreamstime.com/z/%C3%A1rvore-isolada-1821590.jpg">

</div>

<div><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br></div>

这是问题所在:

public Dropdown(){
    super("The title");
    setLayout(new FlowLayout());


    box = new JComboBox (filename); //Automatically put the array in a list for us

    box.addItemListener(
            new ItemListener(){ //automatically implements itemlistener
                public void itemStateChanged(ItemEvent event){ //invoked when dropdown menu button is selected
                    if (event.getStateChange() == ItemEvent.SELECTED) //what icon did you select, prevents you from clicking on itself
                        picture.setIcon(firstpictureinarray[box.getSelectedIndex()]); //change it into that selected icon
                }

            }
    );

    add(box);
    picture = new JLabel (firstpictureinarray [0]);
    add(picture);

}
}

在阅读了很多关于类似错误的内容后,我得出结论,在下面的数组中添加两个元素,但是我得到了一个错误;所以我评论说,增加了部分:

picture.setIcon(firstpictureinarray[box.getSelectedIndex()]); //change it into that selected icon

这是错误:

private Icon[] firstpictureinarray = {new ImageIcon(getClass().getResource(filename [0] /*, filename [1]*/))}; //code = pics

非常感谢您花时间阅读本文,我非常感谢您为帮助其他程序员而付出的努力!

1 个答案:

答案 0 :(得分:1)

firstpictureinarray只包含一个项目,但您的组合框包含多个项目。

尝试像这样定义和初始化firstpictureinarray,以便数组和组合框始终包含相同数量的项目(即文件数):

private Icon[] firstpictureinarray = new Icon[filename.length];
for (int i = 0; i < filename.length; i++) {
    firstpictureinarray[i] = new ImageIcon(getClass().getResource(filename [i]));
}

此外,您应该考虑将“firstpictureinarray”重命名为更准确的内容,例如“picturearray”。