Reputation: 389
I created a JCombobox from sql data. And after i delete the item from combobox, the item still remain until i restart the application again?
I used additem method in a loop to add items to combobox , i have seen people used datamodel but i find this easy.'
code in mainfarme.java
public mainFrame()
{
initComponents();
fillUserCombo();
}
public void fillUserCombo()
{
try {
st=con.createStatement();
rs=st.executeQuery("SELECT `username` FROM `users` WHERE 1");
while(rs.next())
{
username=rs.getString(1);
userCombo.addItem(username);
}
}
catch (SQLException ex)
{
}
}
private void delUesrBtnActionPerformed(java.awt.event.ActionEvent evt) {
user u = new user();
String user =userCombo.getSelectedItem().toString();
u.delUser(user);
}
code in user.java
public void delUser(String user)
{
try
{
this.con=db.getCon();
// System.out.println(user);
String sql="DELETE FROM `users` where (username=?)";
ps=(PreparedStatement)con.prepareStatement(sql);
ps.setString(1,user);
ps.execute();
JOptionPane.showMessageDialog(null,"User Deleted");
mainFrame mf = new mainFrame();
mf.fillUserCombo();
mf.revalidate();
mf.repaint();
}
catch (SQLException ex)
{
Logger.getLogger(user.class.getName()).log(Level.SEVERE, null, ex);
}
}
here deluser deletes the user from the database after the delete button is pressed but after that the combobox item(username) are still there.
i try to call the fillusercombo method again thinking that it will refill the combofox but its the same ,also tried repaint() method.
How do i refresh the combobox? (PS. sorry for the poor style of coding ,still learning ?)
Upvotes: 2
Views: 1313
Reputation: 389
I found the solution on another questions on stack overflow. I think did search there? before i asked anyway here it is
private void delUesrBtnActionPerformed(java.awt.event.ActionEvent evt) {
user u = new user();
String user =userCombo.getSelectedItem().toString();
u.delUser(user);
userCombo.removeAllItems();
fillUserCombo();
}
i remove the all the items using removeAllItems() and again call the fillUserCombo ().
camickr also did mentioned that before but i wan't quite sure how to do that.
Upvotes: 0
Reputation: 324197
mainFrame mf = new mainFrame();
mf.fillUserCombo();
Don't create a new mainframe()
object. This object is just sitting in memory because you don't appear to be doing anything with it.
i have seen people used datamodel but i find this easy.
You have seen this code because it is the proper way to solve the problem. All you need is a reference to the model. Then you remove all the items and add the new items to the model. Or you create a new model and add the model to the combo box.
There is absolutely no good reason to create an entire new frame just to reload data!!!
Upvotes: 4