简体   繁体   English

仅在选择项目时如何从JList获取项目

[英]How to get items from JList only when items are selected

In my program - a JApplet - I have a JList that is populated with a DefaultListModel . 在我的程序(一个JApplet ,我有一个用DefaultListModel填充的JList The user has the choice to select up to a certain number of items and indicate by pressing a JButton that he has finished his / her selection. 用户可以选择最多选择一定数量的项目,并通过按下JButton表明他/她的选择已经完成。 I then use the items selected in the ActionPerformed event handler for the JButton . 然后,我使用在ActionPerformed事件处理程序中为JButton选择的项目。

This works great unless no item is selected before the JButton is pressed - if nothing is selected the rest of the instructions in my ActionPerformed don't operate either. 除非在按下JButton之前未选择任何项目,否则这将非常JButton -如果未选择任何内容,则我的ActionPerformed的其余指令也不会操作。 I have tried myJList.isSelectionEmpty() as an negative if condition and also compared the array length I get from myJList.getSelectedIndices() to 0 but neither work. 我已经尝试将myJList.isSelectionEmpty()为负if条件,并且还将我从myJList.getSelectedIndices()获得的数组长度与0进行了比较,但均myJList.getSelectedIndices()

However, if something is initially clicked and then deselected (I have a clear selection button), it works and in every subsequent time through the program it works, so it seems to be just the first time that it needs to be triggered. 但是,如果最初单击某项然后将其取消选择(我有一个明确的选择按钮),则该控件将起作用,并且在随后的每次程序中都起作用,因此似乎只是第一次需要触发它。

Can anyone point me in the right direction? 谁能指出我正确的方向?

If I understood you well, this might be one solution. 如果我对您的理解很好,那么这可能是一种解决方案。

Initially, disable JButton. 最初,禁用JButton。 Then, provide your JList with ListSelectionListener; 然后,为您的JList提供ListSelectionListener; inside this event handler, check if the selection is made (at least one item selected). 在此事件处理程序中,检查是否已做出选择(至少选择了一项)。 If it is - enable JButton; 如果是,请启用JButton; otherwise disable it. 否则禁用它。 This way you will prevent execution of ActionEvent handler of JButton if no item is selected, which is what you want (I suppose). 这样,如果没有选择任何项(我想),则将阻止执行JButton的ActionEvent处理程序。 Suppose your JList is lstChoices, and your JButton is btnSubmit. 假设您的JList是lstChoices,而您的JButton是btnSubmit。 This should do the above mentioned: 这应该做上面提到的:

lstChoices.addListSelectionListener(new ListSelectionListener() {
        @Override
        public void valueChanged(ListSelectionEvent e)
        {
            if(lstChoices.getSelectedValuesList().size() > 0)
            {
                btnSubmit.setEnabled(true);
            }
            else
            {
                btnSubmit.setEnabled(false);
            }
        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM