Search code examples
javaswingnetbeansselectionjcombobox

Combobox model setselecteditem


I have got the following code:

package nypdapp;

import java.sql.*;
import javax.swing.*;

public class CaseFileAddFrame extends javax.swing.JFrame {

    /**
     * Creates new form CaseFileFrame
     */
    private Connection Econn;
    private int cfid;
    private boolean wijzig;
    private DefaultListModel DetectiveListModel = new DefaultListModel();
    private DefaultListModel EmployeeTotListModel = new DefaultListModel();
    private DefaultListModel WitnessModel = new DefaultListModel();
    private DefaultListModel EvidenceModel = new DefaultListModel();
    private DefaultListModel SuspectsModel = new DefaultListModel();
    private DefaultComboBoxModel DistrictModel = new DefaultComboBoxModel();
    private DefaultComboBoxModel LocationModel = new DefaultComboBoxModel();
    SpinnerModel spmodel = new SpinnerNumberModel(2013,1950,2013,1);
    public CaseFileAddFrame(int cfid, boolean wijzig) {
        initComponents();
        this.cfid = cfid;
        this.wijzig=wijzig;
        s1.setVisible(false);
        s3.setVisible(false);
        s4.setVisible(false);
        YearSn.setModel(spmodel);
        try
        {
            SimpleDataSource.init();
            Econn = SimpleDataSource.getConnection();
        }
        catch(SQLException | ClassNotFoundException e)
        {
            System.out.println(e);
        }
        setDistricts();
        getSelectedDistrict();
        ClassCB.setEnabled(false);
        if(wijzig == true)
        {
            setInformation();
        }        
    }

    private void setLocation(int lid)
    {
        try
        {
            Statement userStat = Econn.createStatement();
            String userquery = "SELECT name, district_name FROM location l INNER JOIN district d ON l.distr_ic = d.district_id WHERE l_id = "+lid;
            ResultSet result = userStat.executeQuery(userquery);
            result.next();
            String name = result.getString("district_name");
            System.out.println("DBName: "+name);
            int i = DistrictModel.getSize();
            for(int p =0; p < i; p++)
            {
                System.out.println("Current:"+DistrictModel.getElementAt(p));
                if(DistrictModel.getElementAt(p).equals(name))
                {
                    //DistrictModel.setSelectedItem(p);
                    DistrictCB.setSelectedIndex(p);
                    System.out.println("Done<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
                }
            }
        }
        catch(SQLException e)
        {
            System.out.println(e);
        }         
    }
   private void setInformation()
    {
        try
        {
            Statement userStat = Econn.createStatement();
            String userquery = "SELECT * FROM casefile WHERE cf_id = "+this.cfid;
            ResultSet result = userStat.executeQuery(userquery);
            result.next();
            switch(result.getInt("crime")) 
            {
                case 0: 
                {
                    CrimeCB.setSelectedIndex(0);
                }
                    break;
                case 1: 
                {
                    CrimeCB.setSelectedIndex(1);
                }
                    break;
                case 2: 
                {
                    CrimeCB.setSelectedIndex(2);
                }
                    break;
                default: 
                {
                    CrimeCB.setSelectedIndex(0);
                }
            }
            if(CrimeCB.getSelectedIndex() == 2)
            {
                ClassCB.setEnabled(true);
            switch (result.getInt("classtype")) 
            {
                case 0: 
                {
                    ClassCB.setSelectedIndex(0);
                }
                    break;
                case 1: 
                {
                    ClassCB.setSelectedIndex(1);
                }
                    break;
                case 2: 
                {
                    ClassCB.setSelectedIndex(2);
                }
                    break;
                case 3: 
                {
                    ClassCB.setSelectedIndex(3);
                }
                    break;
                case 4: 
                {
                    ClassCB.setSelectedIndex(4);
                }
                    break;
                case 5: 
                {
                    ClassCB.setSelectedIndex(5);
                } 
                    break;
                case 6: 
                {
                    ClassCB.setSelectedIndex(6);
                }
                    break;
                case 7: 
                {
                    ClassCB.setSelectedIndex(7);
                }
                    break;
                case 8: 
                {
                    ClassCB.setSelectedIndex(8);
                }  
                    break;
                default: 
                {
                    ClassCB.setSelectedIndex(0);
                }
            }
            }
            else
            {
                ClassCB.setEnabled(false);
            }

            switch (result.getInt("type")) 
            {
                case 0: 
                {
                    TypeCB.setSelectedIndex(0);
                }
                    break;
                case 1: 
                {
                    TypeCB.setSelectedIndex(1);
                }
                    break;
                case 2: 
                {
                    TypeCB.setSelectedIndex(2);
                }
                    break;
                case 3: 
                {
                    TypeCB.setSelectedIndex(3);
                }
                    break;
                case 4: 
                {
                    TypeCB.setSelectedIndex(4);
                }
                    break;
                case 5: 
                {
                    TypeCB.setSelectedIndex(5);
                } 
                    break;
                case 6: 
                {
                    TypeCB.setSelectedIndex(6);
                }
                    break;
                case 7: 
                {
                    TypeCB.setSelectedIndex(7);
                }
                    break;
                case 8: 
                {
                    TypeCB.setSelectedIndex(8);
                }       
                    break;
                default: 
                {
                    TypeCB.setSelectedIndex(0);
                }
            }
            SubjectTF.setText(result.getString("subject"));
            Date date = result.getDate("date");
            int month = date.getMonth();
            int day = date.getDate();
            int year = date.getYear()+1900;
            MonthCB.setSelectedIndex(month);
            DayCB.setSelectedIndex(day);
            spmodel.setValue(year);
            AssignedDATF.setText(result.getString("assignedDA"));
            FRNameTF.setText(result.getString("fr_id"));
            DescriptionTA.setText(result.getString("description"));
            setLocation(result.getInt("lid"));
        }
        catch(SQLException e)
        {
            System.out.println(e);
        }       
    }    
    private void setDistricts()
    {
        try
        {
            Statement userStat = Econn.createStatement();
            String userquery = "SELECT district_id, district_name FROM district";
            ResultSet userResult = userStat.executeQuery(userquery);
            while(userResult.next())
            {
               int ids = userResult.getInt("district_id");
               String name = userResult.getString("district_name");
               DistrictModel.addElement(new DistrictItem(name,ids));
            }
            DistrictCB.setModel(DistrictModel);
        }
        catch(SQLException e)
        {
            System.out.println(e);
        }
    }                                              

    private void SubmitCaseFileButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                     
        if(validation() == false)
        {
            javax.swing.JOptionPane.showMessageDialog(null, "WARNING\nCheck the field validation!\nIf there is no Assigned DA Enter 'Unknown'");
        }
        else if(wijzig == false)
        {
            int crime = CrimeCB.getSelectedIndex();
            int crimeclass;
            if(ClassCB.isEnabled() == true)
            {
                crimeclass = ClassCB.getSelectedIndex();
            }
            else
            {
                crimeclass = 0;
            }
            String subject = SubjectTF.getText();
            int month = MonthCB.getSelectedIndex()+1;
            int day = DayCB.getSelectedIndex()+1;
            int year = Integer.parseInt(spmodel.getValue().toString());
            Date date = ToSQLClass.toSqlDate(year, month, day);
            int crimetype = TypeCB.getSelectedIndex();
            LocationSItem li = (LocationSItem)LocationCB.getSelectedItem();
            int locationid = li.id;
            String assignedDA = AssignedDATF.getText();
            String description = DescriptionTA.getText();
            String fr = FRNameTF.getText();
            try
            {
                PreparedStatement addstat = Econn.prepareStatement("INSERT INTO casefile VALUES(cf_id,?,?,?,?,?,?,?,?,?,?)");
                addstat.setString(1, subject);
                addstat.setInt(2, crime);
                addstat.setInt(3, crimetype);
                addstat.setString(4, description);
                addstat.setString(5, assignedDA);
                addstat.setString(6, fr);
                addstat.setNull(7,java.sql.Types.INTEGER);
                addstat.setDate(8, date);
                addstat.setInt(9, crimeclass);
                addstat.setInt(10, locationid);
                addstat.execute();    
                javax.swing.JOptionPane.showMessageDialog(null, "WARNING\nCasefile added!\n\nDon't forget to add suspects, witnesses, detectives and evidence!");
                this.dispose();
            }
            catch(SQLException e)
            {
                System.out.println(e);
            }
        }
        else
        {
            int crime = CrimeCB.getSelectedIndex();
            int crimeclass;
            if(ClassCB.isEnabled() == true)
            {
                crimeclass = ClassCB.getSelectedIndex();
            }
            else
            {
                crimeclass = 0;
            }
            String subject = SubjectTF.getText();
            int month = MonthCB.getSelectedIndex()+1;
            int day = DayCB.getSelectedIndex()+1;
            int year = Integer.parseInt(spmodel.getValue().toString());
            Date date = ToSQLClass.toSqlDate(year, month, day);
            int crimetype = TypeCB.getSelectedIndex();
            LocationSItem li = (LocationSItem)LocationCB.getSelectedItem();
            int locationid = li.id;
            String assignedDA = AssignedDATF.getText();
            String description = DescriptionTA.getText();
            String fr = FRNameTF.getText();
            try{
            Statement addstat = Econn.createStatement();            
            addstat.executeUpdate("UPDATE casefile SET subject = '" + subject
                       + "' ,assignedDA = '" + assignedDA
                       + "' ,description = '" + description
                       + "' , fr_id = '" + fr
                        +"',date = '"+date
                        +"' ,crime = "+crime
                        +" ,crimeclass = " +crimeclass
                        +" ,crimetype = " +crimetype
                        +" ,lid = " +locationid
                       + " WHERE cf_id = " + this.cfid);         
            }
            catch(SQLException e) { System.out.println(e); }
        }
    }                                                                                           
    private void getSelectedDistrict()
    {
        try
        {
            LocationModel.removeAllElements();
            DistrictItem di = (DistrictItem)DistrictCB.getSelectedItem();
            Statement userStat = Econn.createStatement();
            String userquery = "SELECT l_id, name FROM location WHERE distr_ic = "+di.id;
            ResultSet userResult = userStat.executeQuery(userquery);
            while(userResult.next())
            {
               int ids = userResult.getInt("l_id");
               String name = userResult.getString("name");
               LocationModel.addElement(new LocationSItem(ids,name));
            }
            LocationCB.setModel(LocationModel);
        }
        catch(SQLException e)
        {
            System.out.println(e);
        }
    }
    private void DistrictCBItemStateChanged(java.awt.event.ItemEvent evt) {                                            
        getSelectedDistrict();
    }                                           

    private void CrimeCBItemStateChanged(java.awt.event.ItemEvent evt) {                                         
        if(CrimeCB.getSelectedIndex() == 2)
        {
            ClassCB.setEnabled(true);
        }
        else
        {
            ClassCB.setEnabled(false);
        }
    }                
}

The DistrictModel contains every district retrieved from the setDistricts() method.

I think it is pretty self explanatory what it does. Thing is, it never enters the if-statement (even though it prints all items in de districtmodel.getelementat) so it does run correctly through the for loop.


Solution

  • OK. The answer is simple now that we can see the code. The district model contains instances of DistrictItem:

    DistrictModel.addElement(new DistrictItem(name,ids));
    

    And you compare every element of this model with a String. So obviously, the comparison will always be false, because a DistrictItem can't be equal to a String. Only a String can be equal to a String.

    So, assuming the district names are unique (but you should probably use the ID rather than the name), you should iterate through the elements and find the one which has the same name as the one you retrieved:

    int i = DistrictModel.getSize();
    for (int p = 0; p < i; p++) {
        DistrictItem currentDistrictItem = (DistrictItem) DistrictModel.getElementAt(p);
        if (currentDistrictItem.getName().equals(name)) {
            DistrictCB.setSelectedIndex(p);
            break;
        }
    }
    

    Also, you should respect the Java naming conventions: variables start with a lwoercase letter: districtModel instead of DistrictModel (and same for all the other variables)