I'm new, but I was searching and now it's time for me to ask you mates. I have this simple app in java, which includes itemListener for JComboBox. I have no idea why but, it doesn't listen, but when i put JComboBox upper in hierarchy it works, and itemListener works fine. Any ideas why it doesn't work in lower level?
import javax.swing.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
public class Notatnik extends JFrame {
JMenuBar menu;
JMenu tools, fontColor;
JComboBox<String> colors;
public Notatnik() {
this.setSize(500, 400);
menu = new JMenuBar();
tools = new JMenu("tools");
fontColor = new JMenu("Font color");
colors = new JComboBox<String>();
colors.addItem("red");
colors.addItem("green");
colors.addItem("blue");
colors.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
System.out.println(e.getItem().toString());
}
});
fontColor.add(colors);
tools.add(fontColor);
menu.add(tools);
this.setJMenuBar(menu);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
}
It is not possible to add a
JComboBoxto aJMenucomponent (without destroying the listeners). Therefore, I changed the implementation a bit:I know that the code is not tidy or efficient, but it works just fine. Before I forget it, you should definetly visit this article about when to inherit a class.