Java JFrame ComboBox情况

时间:2013-06-07 17:23:39

标签: java swing jdbc jcombobox comboboxmodel

我在Jframe中遇到此问题。我使用JComboBox来显示用户的一些选择(来自日期库),他选择了一个选项,然后在重新运行initComponents()后,我想排除这个选择并仅显示其余部分。但是对于某些人来说原因无论我如何编辑代码,它一直显示相同。有什么建议? Thx提前(随时问我什么)。

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);
            }
        }
    }
}

** * ** * ** * 的** * (这是整个代码) * ** * ** * ** * ** * ** * ** * ****  @SuppressWarnings( “未登记”)

// <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                   

}

1 个答案:

答案 0 :(得分:2)

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

不,它不是组合框显示的模型。它是模型的新创建的本地实例。您永远不会将此模型实例添加到组合框中。

假设您已在代码中的某处定义了名为“m”的类变量,则无需创建新模型。只需清除现有模型,然后添加数据库查询中的元素即可。

编辑:

在您发布部分代码之前。您现在添加了更多代码,我看到了以下几行:

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

现在你创建一个新的comboBox并将模型添加到它。

问题是您没有将新创建的comboBox添加到框架中,因此您永远不会看到更新。更新变量的引用与将组件添加到框架不同。

您需要删除创建新comboBox的行,或者需要将新的comboBox添加到框架中。

将来发布问题时,您需要发布一个SSCCE来证明您的问题。