I've created a JFrame
window with a JComboBox
. I can select things but they don't do anything. I thought that event
was a String
, but it isn't. What is the solution for this?
import java.awt.FlowLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Gui extends JFrame {
private JComboBox box;
private JLabel picture;
private static String[] filename = {"", "b.png", "x.png"};
public Gui() {
super("the title");
setLayout(new FlowLayout());
box = new JComboBox(filename);
box.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent event) {
if(event.getStateChange()==ItemEvent.SELECTED){
System.out.println("test");
if(event=="b.png") {
System.out.println("test2");
}
}
}
});
add(box);
}
}
You need to get the selected item (which is a String
in your case) and compare it to your string with equals
:
if ("b.png".equals(event.getItem()))
Note that this is preferable to
event.getItem().equals("b.png")
since this can theoretically throw a NPE.
Also, use a generic type: JComboBox<String>
, not the raw type.