栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Java-如果在combox1中选择了一个值,则应在所有其他组合框中将其禁用

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Java-如果在combox1中选择了一个值,则应在所有其他组合框中将其禁用

不知道您的两个答案中的哪个将被删除,但是这里又是相同的答案。请注意,您可以使用循环创建所有JComboBoxes和选项,以防止真正冗长的重复代码。然后,您可以使用getSource()方法来判断事件来自哪个组合框。如果将JComboBoxes创建为数组,则可以非常清晰地循环遍历它们。为了重新添加内容,我只需要跟踪已选择的内容以及使用String数组的组合框。然后,您可以检查此数组,并根据需要使用它来添加项目。请注意,它们不会以相同的顺序返回。如果您想要该功能,则可以使用insertItemAt,但这可能会有些混乱(因为自从添加和删除项以来索引一直在变化),因此我将其省略。

//Declare and initialize the options that the comboboxes will haveString[] options = {"-Select-", "Item 1", "Item 2", "Item 3", "Item 4"};//Declare and initialize an array that will hold the currently selected options in each combobox by index//For example the currently selected value of comboBoxes[1] is selected[1]String[] selected = {"-Select-", "-Select-", "-Select-", "-Select-"};//Declare and initialize an array of comboBoxes. //Four comboboxes will be created all containing the options arrayJComboBox[] comboBoxes = new JComboBox[4];for(int i = 0; i < comboBox.length; i++) {    comboBoxes[i] = new JComboBox(options);}private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {    //Loop through all of the comboboxes in comboBoxes    for(int i = 0; i < comboBoxes.length; i++) {        //Check to see if the current combobox in the array matches the source of your event        if(evt.getSource() == comboBoxes[i]) { //Get the string value of the combobox that fired the event String currentSelection = (String)comboBoxes[i].getSelectedItem(); //Make sure that the value actually changed if(!currentSelection.equals(selected[i]) {     //If the previous value of the combobox was "-Select-" don't add it to all the other comboboxes     if(!selected[i].equals(options[0])) {         //Add back the previous value to all comboboxes other than the one that fired the event         for(int j = 0; j < comboBoxes.length; j++) {  if(j != i) {      comboBoxes[j].addItem(selected[i]);  }         }     }     //If current value of the combobox is "-Select-" don't remove it from all other comboboxes     if(!currentSelection.equals(options[0]) {         //Remove the current value from all comboboxes other than the one that fired the event         for(int j = 0; j < comboBoxes.length; j++) {  if(j != i) {      comboBoxes[j].removeItem(comboBoxes[i].getSelectedItem());  }         }     } } //Set the selected item for the combobox that fired the event to the current value selected[i] = currentSelection;        }    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419571.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号