Question

I have this problem in a Jframe. I use a JComboBox to display some choices for the user(from a datebase), he picks a choice and then after rerunning initComponents(), I want to exclude this choice and show only the rest.But for some reason no matter how i edit code it keeps showing the same. Any suggestions? Thx in advance (feel free to ask me whatever).

private void initComponents() {
    jLabel1 = new javax.swing.JLabel();
    DefaultComboBoxModel m=new DefaultComboBoxModel();//this is the m which is //displayed by the combobox
    try//try to connect to database
    {
        Connection conn=new DBconnect().con();
        Statement stmt=new DBconnect().stm(conn);

        final ResultSet rs = stmt.executeQuery( "SELECT * FROM BILL WHERE CUSTOMER_CODE="+login.password+" AND BILL_TYPE='contract'") ;//get the data from sql

        m.removeAllElements();
        while(rs.next()){//get the date to string
            String nbill=(rs.getString("telephone")+" Program:"+rs.getString("programm")+" Remaind Free Time:"+rs.getString("remaind_free_time"));
            //The user selects the telephone (tel) and then rerunning the INitComponents here we test 

            if(rs.getString("telephone").equals(tel)){

                System.out.println("ok");
                m.removeElement(nbill);
                //I putted continue here instead else here but the same 

            }
            else{
                m.addElement(nbill);
            }
        }
    }
}

************(That's the whole code)*********************** @SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jLabel1 = new javax.swing.JLabel();
    DefaultComboBoxModel m=new DefaultComboBoxModel();
    try
    {
        Connection conn=new DBconnect().con();
        Statement stmt=new DBconnect().stm(conn);

        final ResultSet rs = stmt.executeQuery( "SELECT * FROM BILL WHERE CUSTOMER_CODE="+login.password+" AND BILL_TYPE='contract'") ;

        //erase stuff not needed
        m.removeAllElements();
        while(rs.next()){
            String nbill=(rs.getString("telephone")+" Program:"+rs.getString("programm")+" Remaind Free Time:"+rs.getString("remaind_free_time"));

            if(rs.getString("telephone").equals(tel)){
                System.out.println("ok");
                m.removeElement(nbill);

            }
            else{
                m.addElement(nbill);
            }
        }
        /*  for(String nbill : m){
            if(nbill.substring(0,10).equals(tel)){
                m.removeElement(nbill);}
        }*/
        jComboBox1 = new javax.swing.JComboBox();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("Επιλέξτε το Συμβόλαιο από το οποίο επιθυμείτε να πάρετε χρόνο");

        jComboBox1.setModel(m);
        jComboBox1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jComboBox1KeyPressed(evt);
            }
        });
    }
    catch( SQLException se )
    {
        System.out.println( "SQL Exception:" ) ;

        // Loop through the SQL Exceptions
        while( se != null )
        {
            System.out.println( "State  : " + se.getSQLState()  ) ;
            System.out.println( "Message: " + se.getMessage()   ) ;
            System.out.println( "Error  : " + se.getErrorCode() ) ;

            se = se.getNextException() ;
        }
    }
    catch( Exception e )
    {
        System.out.println( e ) ;
    }

    jLabel2.setText("Ή esc για επιστροφή στο κεντρικό menu");

    jLabel3.setText("και πατήστε enter");

    jLabel4.setText("(Η μεταφορά χρόνου ισχυεί για όμοια πργ.)");

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(40, 40, 40)
                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 343, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createSequentialGroup()
                    .addGap(52, 52, 52)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addGap(18, 18, 18)
                            .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1)))))
            .addContainerGap(42, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGap(22, 22, 22)
            .addComponent(jLabel1)
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel3)
                .addComponent(jLabel4))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 182, Short.MAX_VALUE)
            .addComponent(jLabel2)
            .addGap(26, 26, 26))
    );

    pack();
}// </editor-fold>                        

private void jComboBox1KeyPressed(java.awt.event.KeyEvent evt) {                                      
     if(evt.getKeyCode()==evt.VK_ENTER){
            if("0".equals(login.password.substring(0,1))){
            this.setVisible(false);
           // choose_option_man of = new choose_option_man();
            //of.setVisible(true);
            }
            else if("1".equals(login.password.substring(0,1))){
            //if(ξεκινάει από 0 ή 1....)
            this.setVisible(false);
          //  choose_option_company of = new choose_option_company();
           // of.setVisible(true);
            }

            if(jComboBox1.getSelectedItem()!=null){
                    String choice=(String) jComboBox1.getSelectedItem();
                    //int i = choice.lastIndexOf(":");

                    tel = choice.substring(0,10);//telephone fetched
                    //ok System.out.println("telephone"+tel);

                    String FreeTime = choice.substring(41,44);
                    int FreeTimeN = Integer.parseInt(FreeTime);//remaining free time fetched
                    //ok System.out.println("NUmber"+FreeTimeN);

                   /* this.setVisible(false);
                    TransferInput of = new TransferInput();///with another Jframe
                    of.setVisible(true);*/

            /*        JTextField new_text = new JTextField("Test text");
                    JDialog new_dialog = new JDialog(Test_Contracts, "Test");
                    new_dialog.pack();
                    new_dialog.setVisible(true);
                    new_dialog.toFront();
                    new_dialog.setSize(500,150);
                    new_dialog.setLocation(500,500);
                    new_dialog.add(new_text);               */

                    String TimeTransfer = JOptionPane.showInputDialog ( "Βάλτε το χρόνο" ); //put here Time for transfer
                    int TimeTransferN = Integer.parseInt(TimeTransfer);
                    if(TimeTransferN>FreeTimeN){
                        JOptionPane.showMessageDialog(null,"Ανεπιτυχής συναλλαγή χρόνου!", "Inane error",JOptionPane.ERROR_MESSAGE);//αντι null frame???
                        //get back to main menu with visible
                    }
                    else{
                        //xXx=true;
                        initComponents();
                        this.setVisible(true);
                    }


            }

   }
   else if(evt.getKeyCode()==evt.VK_ESCAPE){
        if("0".equals(login.password.substring(0,1))){
            this.setVisible(false);
            choose_option_man of = new choose_option_man();
            of.setVisible(true);
            }
            else if("1".equals(login.password.substring(0,1))){
            //if(ξεκινάει από 0 ή 1....)
            this.setVisible(false);
            choose_option_company of = new choose_option_company();
            of.setVisible(true);
            }
    }

}                                     

/**
 * @param args the command line arguments
 */
public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(Test_Contracts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (InstantiationException ex) {
        java.util.logging.Logger.getLogger(Test_Contracts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (IllegalAccessException ex) {
        java.util.logging.Logger.getLogger(Test_Contracts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    } catch (javax.swing.UnsupportedLookAndFeelException ex) {
        java.util.logging.Logger.getLogger(Test_Contracts.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new Test_Contracts().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JComboBox jComboBox1;

private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;

// End of variables declaration                   

}

Was it helpful?

Solution

//this is the m which is displayed by the combobox 
DefaultComboBoxModel m=new DefaultComboBoxModel();

No it is not the model displayed by the combobox. It is a newly created local instance of the model. You never add this instance of the model to the combo box.

Assuming you have define a class variable called "m" somewhere in your code then there is no need to create a new model. Just clear the existing model and then add the elements from your database query.

Edit:

Before you only posted part of the code. You now added more code and I see the lines:

jComboBox1 = new javax.swing.JComboBox();
...
jComboBox1.setModel(m);

So now you create a new comboBox and add the model to it.

The problem is that you didn't add the newly created comboBox to the frame so you never see the updates. Updating the reference of a variable is not the same as adding the component to the frame.

You either need to delete the line that creates a new comboBox or you need to add the new comboBox to the frame.

In the future when you post a question you need to post a SSCCE which demonstrates your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top