I've been making a program where it will ask the user to input in the JTextField how many Departments it will add. Once clicked enter, it will go through a for-loop which then will create the same amount you've entered.
While making the program, I've thought of where I wanted to make it wherein once you selected an item to the first JComboBox, the rest of the JComboBoxes will have no more of that item you've selected in the previous one. However, I don't seem to understand how will I code it.
For instance, JComboBox A, B and, C have items: "Fire", "Water" and "Wind".
Once you've selected the item: "Fire" for A, JComboBox B and C should have items: "Water" and "Wind" left on their selection. Lastly, selecting item: "Wind" on B will have the remaining item: "Water" to C.
From the program I've created, this button will create the JComboBoxes after inputting a number from the TextField:
JButton enterButton = new JButton("Enter");
enterButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
listCB.clear();
deptContent.removeAll();
int count = Integer.valueOf(textField.getText());
for(int i = 0; i < count; i++) {
JComboBox<String> cb = new JComboBox<String>();
cb.addItem("Select a department");
dept(cb); // this function will add the items in cb
cb.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {
if(cb.getSelectedIndex() > 0) {
selectedDept = cb.getSelectedItem().toString();
obtainedDeptNames.add(selectedDept);
} else {
obtainedDeptNames.remove(selectedDept);
}
revalidate();
repaint();
}
}
});
listCB.add(cb);
deptContent.add(cb);
}
revalidate();
repaint();
}
});
Here's the dept() function:
private void dept(JComboBox<String> cb) {
try (Connection conn = DriverManager.getConnection(MySQLConnectivity.URL, MySQLConnectivity.user ,MySQLConnectivity.pass)){
PreparedStatement getStatement = conn.prepareStatement("select departmentname from departmentinfo where schoolname='"+obtainedSchoolName+"'");
ResultSet result = getStatement.executeQuery();
while(result.next()) {
String obtainedDept = result.getString("departmentname");
cb.addItem(obtainedDept);
}
} catch (SQLException sql) {
sql.printStackTrace();
}
}
How will I do the problem I'm facing? Answers will be appreciated, thank you!