[英]How to make string get elements from an array based on the combobox array
I miss something and I will appreciate your help I have this array for a combobox 我想念一些东西,感谢您的帮助,我有这个数组用于组合框
String array [] = {"aa", "bb", "cc"};
and I have this for loop to run all over the array 我有这个for循环在整个数组上运行
for(String s: array) {
if(s.equals(array[0]) {
//do something
}
}
Now what I need is that, I need the "do something" to happen to each element in the array only when the element is selected by the combobox, my array is so long and I can't write if statement for each element in the array. 现在,我需要的是,仅当组合框选择了元素时,我才需要对数组中的每个元素执行“操作”,我的数组是如此之长,并且我无法为if中的每个元素编写if语句数组。
What I want is something like that 我想要的就是这样
for(String s : array) {
if(s equals the array elements) {
substring the first index of each element
print s
so result let's say will be like this
a ----> if only element a is selected
b ----> if only element b is seleceted
etc ...
}
}
This fixed my problem, thank you all and sorry for disturbing you 这解决了我的问题,谢谢大家,对不起打扰您了
for(String s: arrar) {
if(combobox.getSelectedItem().equals(s)) {
do something;
}
}
As px06 said, you might want to add an event listener on your Combobox and then handle item selection. 如px06所述,您可能想在组合框上添加事件侦听器,然后处理项目选择。 Here is code snippet for what you are looking for:
这是您要查找的代码片段:
String[] array = {"aa", "bb", "cc"};
JComboBox comboBox = new JComboBox(array);
comboBox.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
JComboBox<String> combo = (JComboBox<String>) event.getSource();
String selectedItem = (String) combo.getSelectedItem();
if (selectedItem.equals("<some-choice>")) {
//do something
} else if (selectedItem.equals("<some-other-choice>")) {
//do something else...
}
}
});
However I do not see how you can escape checking which item was selected if you want to do something specific based on selection. 但是,如果要基于选择进行特定的操作,我看不到如何逃避检查选择了哪个项目。
I hope this helps. 我希望这有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.