I'm working on a simple hospital appointment system. My comboboxes are dependant one to another.
.
The issue is when I click the City combobox and select a city, it enters the county actionListener too. Why?
private void initialize() {
City cities = new City();
Hospital hospitals = new Hospital();
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblCity = new JLabel("City");
lblCity.setBounds(25, 25, 25, 14);
frame.getContentPane().add(lblCity);
JComboBox<String> cityBox = new JComboBox<String>(); // CITY
JComboBox<String> hospitalBox = new JComboBox();
hospitalBox.setBounds(99, 141, 265, 22);
frame.getContentPane().add(hospitalBox);
JComboBox<String> comboClinic = new JComboBox<String>(); // CLINIC
comboClinic.setEditable(true);
comboClinic.setBounds(99, 101, 265, 22);
frame.getContentPane().add(comboClinic); // CLINIC
JComboBox<String> countyBox = new JComboBox<String>(); // COUNTY
countyBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// do something
});
countyBox.setEditable(true);
countyBox.setBounds(99, 61, 265, 22);
frame.getContentPane().add(countyBox); // COUNTY
cityBox.setEditable(true); // CITY
cityBox.addItem("Istanbul");
cityBox.addItem("Ankara");
cityBox.addItem("Izmir");
cityBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (cityBox.getSelectedItem().equals("Istanbul")) {
countyBox.removeAllItems(); hospitalBox.removeAllItems();
String istanbul[] = cities.getIstanbul();
countyBox.setSelectedItem("Select county");
for (int i = 0; i < istanbul.length; i++) countyBox.addItem(istanbul[i]);
comboClinic.setSelectedItem("Select clinic");
}
else if(cityBox.getSelectedItem().equals("Ankara")) {
countyBox.removeAllItems(); hospitalBox.removeAllItems();
String ankara[] = cities.getAnkara();
countyBox.setSelectedItem("Select county");
for (int i = 0; i < ankara.length; i++) countyBox.addItem(ankara[i]);
comboClinic.setSelectedItem("Select clinic");
}
else if(cityBox.getSelectedItem().equals("Izmir")) {
countyBox.removeAllItems(); hospitalBox.removeAllItems();
String izmir[] = cities.getIzmir();
countyBox.setSelectedItem("Select county");
for (int i = 0; i < izmir.length; i++) countyBox.addItem(izmir[i]);
comboClinic.setSelectedItem("Select clinic");
}
}
});
cityBox.setSelectedItem("Select City");
cityBox.setBounds(99, 21, 265, 22);
frame.getContentPane().add(cityBox); // CITY
as you can see there when i select a city, it arranges the cities counties but it also enters the county actionListener too
Within your event-handling block, you make the following call:
countyBox.setSelectedItem("Select county");
Per the javadoc on JComboBox
ActionListeners added to the combo box will be notified with an ActionEvent when this method is called.
Thus, you the ActionListener
you have added to the countyBox
is responding.