我一直在尝试通过更改框旁边的JLabel图像来使侦听器(我不确定我应该使用ItemListener还是ActionListener)来响应JComboBox中的更改。
我尝试在组合框上的addActionListener调用下以及在构造函数外部的类的构造函数中定义actionPerformed方法,而actionPerformed似乎从未执行。我在每个对话框中都添加了一个println,以测试当我在框中选择一个项目时该方法是否真正起作用,但是没有一个似乎输出任何东西,这使我相信actionPerformed方法由于某种原因未在执行。在其他地方,有许多不同的答案在多个不同的地方定义了actionListeners和actionPerformed,例如一个单独的类或一个实例变量声明。
public class MainBattle
{
//instance variables
public MainBattle() throws FileNotFoundException,IOException
{
//creation of ArrayLists used later
for(JComboBox<String> j : party1)
{
j.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("Listener active");
if(e.getSource() instanceof JComboBox)
{
JComboBox<String> cb = (JComboBox<String>)e.getSource();
String content = (String)cb.getSelectedItem();
if(party1.indexOf(cb) != -1)
{
party1Image.get(party1.indexOf(cb)).setIcon(new ImageIcon(".\\res\\sprites_small\\"
+ content.substring(0,content.indexOf(" ")) + ".png"));
}
}
selectFrame.revalidate();
selectFrame.repaint();
}
});
}
createUI();
}
public void createUI()
{
//building GUI elements and displaying
for(int i = 0; i < 6; i++)
{
party1.add(new JComboBox<String>());
party2.add(new JComboBox<String>());
}
for(int i = 0; i < 6; i++)
{
party1Image.add(new JLabel(new ImageIcon(".\\res\\sprites_small\\0.png")));
party2Image.add(new JLabel(new ImageIcon(".\\res\\sprites_small\\0.png")));
}
//building GUI elements and displaying
}
// Commented out to make sure existence of multiple methods is not problematic
/*
public void actionPerformed(ActionEvent e)
{
System.out.println("Action");
}
*/
public static void main(String[] args) throws IOException
{
new MainBattle();
}
}