我正在尝试向JComboBox添加动作侦听器,但出于某种原因,每次单击JComboBox时,我选择的所选项目不是seasonsBox(那个框).getSelectedItem()和seasonsBox.getSelectedItem( )实际上是框中的第一项。这是我的(相关)代码; (我添加了setupSeasonsBox,因为它可能有问题)
public void setupSeasonsBox(Show currentShow){
seasonsBox.addItem("Choose a season");
seasonsBox.setBounds(0,50,500,20);
seasonsBox.setVisible(true);
panel.add(seasonsBox);
if(currentShow.getSeasons()==null||currentShow.getSeasons().size()==0){
}else if(seasonsBox.getItemCount()<=2){
Season[] seasons = currentShow.getSeasons().toArray(new Season[currentShow.getSeasons().size()]);
List<Integer> numberslist = new ArrayList<Integer>();
for(Season season : seasons){
numberslist.add(season.getNumber);
}
Integer[] numbers = numberslist.toArray(new Integer[numberslist.size()]);
Arrays.sort(numbers, new Comparator<Integer>(){public int compare(Integer x, Integer y){return x - y;}});
for(Integer i : numbers){
seasonsBox.addItem("Season "+i);
}
}
//Remove duplications
Set<String> items = new HashSet<String>();
for(int i = 0; i<seasonsBox.getItemCount(); i++){
items.add(seasonsBox.getItemAt(i));
}
seasonsBox=new JComboBox<String>(items.toArray(new String[items.size()]));
}
public void actionChooseSeason(){
ActionListener ac = new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("PREFORMED");
System.out.println(seasonsBox.getSelectedItem());
if(seasonsBox.getSelectedItem()!="Choose a season"&&
seasonsBox.getSelectedItem()!="No seasons found."){
Season currentSeason = getSeasonByNumber(currentShowSelected,Integer.parseInt(seasonsBox.getSelectedItem().toString().replaceAll("Season ","")));
setupEpisodesBox(currentSeason);
System.out.println(currentSeason==null);
currentSeasonSelected=currentSeason;
}else{
if(episodeBox!=null)if(episodeBox.isVisible())episodeBox.setVisible(false);
currentSeasonSelected=null;
}
}
};
seasonsBox.addActionListener(ac);
}
操作已注册,触发时会调用 ,但问题出在所选项目上。它不会执行操作,因为它始终是相同的项目,并且该项目不会触发我想要触发的操作。