选定项目arraylist的java索引

时间:2018-07-02 16:26:10

标签: java arraylist indexof

在Java中,我试图确定刚刚单击了ArrayList中的哪个JComboBox。一些代码如下:

<!DOCTYPE html>
<html>
    <head>
        <title>Nick's site</title>
        <link rel="stylesheet" type="text/css" href="./styles3.css">
        <meta name="viewport" content="width= device-width, inital-scale=1">
    </head>
    <body>
        <div id="page-1" class="page">
            <div id="work">
                <div id="workButton" class="category-container center">
                    <a class="category-button pointer" onclick="openSites('work')">Work</a>
                </div>
                <div id="workSites" class="hide">
                    <ul class="sites center">
                        <li class="site"><a class="pointer" href="#">Printfactory</a></li>
                        <li class="site"><a class="pointer" href="#">Henry's Site</a></li>
                    </ul>
                    <button onclick="reset('work')" class="buttonClose pointer" style="z-index: 2;">
                        Reset
                    </button>
                </div>
            </div>
        </div>
        <div id="page-2" class="page">
            <div id="other">
                <div id="otherButton" class="category-container center">
                    <a class="category-button pointer" onclick="openSites('other')">Other</a>
                </div>
                <div id="otherSites" class="hide">
                    <ul class="sites center">
                        <li class="site"><a class="pointer" href="#">#</a></li>
                        <li class="site"><a class="pointer" href="#">#</a></li>
                        <li class="site"><a class="pointer" href="#">#</a></li>
                    </ul>
                    <button onclick="reset('other')" class="buttonClose pointer" style="z-index: 2;">
                        Reset2
                    </button>
                </div>
            </div>
        </div>
    </body>
</html>

我的问题是,当我单击并更改其中一个组合框时,显示的索引始终为-1。我想获取数组列表中刚刚单击/更改的框的索引。没有显式类型转换,我得到相同的结果。

1 个答案:

答案 0 :(得分:2)

问题出在这段代码中:

for(int i=0; i<2; i++) {
    JComboBox<String> jcb = new JComboBox<String>(str);
    setTextBoxList.add(new JComboBox<String>(str)); // <-- error!
    jcb.addActionListener(this);
}

您正在创建两个JComboBox,而获得侦听器的不是列表中的那个。尝试将代码更改为:

for(int i=0; i<2; i++) {
    JComboBox<String> jcb = new JComboBox<String>(str);
    setTextBoxList.add(jcb); // changed line
    jcb.addActionListener(this);
}