简体   繁体   中英

How can I prevent my jComboBox from resetting?

I have a ResultSet . This ResultSet is filling a JComboBox with data like this:

DatabaseHandler dh = new DatabaseHandler();

public ResultSet Klanten;

public BestellingenNieuwPanel() {
    initComponents();
    //Removes all items from KlantBox.
    KlantBox.removeAllItems();
    //Removes all from ProductBox.
    ProductBox.removeAllItems();
        try {
        Klanten = dh.getDataFromDB("select * from klanten");
        while (Klanten.next()) {
            String strKlanten = Klanten.getString("Achternaam");
            KlantBox.addItem(Klanten.getString(3));
        }

    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

This workes just fine. But, whenever I try to loop through ResultSet Klanten again like this:

private void KlantBoxActionPerformed(java.awt.event.ActionEvent evt) {  

    if(Klanten != null){
        String strSelected = KlantBox.getSelectedItem().toString();            
        try {
            while(Klanten.next()){
                String KlantVoornaam = Klanten.getString(1);
                String KlantAchternaam = Klanten.getString(2);
                String KlantWoonplaats = Klanten.getString(4);
                if(strSelected == KlantAchternaam){
                    txtKlantNaam.setText(KlantAchternaam);
                    txtKlantWoonplaats.setText(KlantWoonplaats);
                }
            }
        } catch (SQLException ex) {
        }

    }
}      

My JComboBox Klanten only has it's last value. I've fiddled around with the Klanten.next() function and found that that function is the source of the problem.

Are there any other ways to loop through a ResultSet ? Or is there a way to loop through a ResultSet WITHOUT resetting my JComboBox ?

Don't compare strings like this if(strSelected == KlantAchternaam){ use equals() instead.

But in fact after refreshing the combobox just call setSelectedItem(strSelected )

I think the error is with your comparison of string using == rather than with your use of Klanteen.next()

Try using the following code

if(strSelected.equals(KlantAchternaam)){
                txtKlantNaam.setText(KlantAchternaam);
                txtKlantWoonplaats.setText(KlantWoonplaats);
            }

or this one, if you want to ignore case

if(strSelected.equalsIgnoreCase(KlantAchternaam)){
                txtKlantNaam.setText(KlantAchternaam);
                txtKlantWoonplaats.setText(KlantWoonplaats);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM