如何在ComboBox中获取输入?

时间:2015-08-14 01:21:09

标签: java swing jcombobox

我尝试获取组合框值,但它无法检索输入。我使用NetBeans软件。这对我来说很复杂。除此之外,我需要大家帮我解决这个问题。希望有人可以帮助我..

public class Lab4 extends javax.swing.JPanel {


    public Lab4() {
        initComponents();

    }


    }                                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
 {
        int num1,num2,sum;
        num1=Integer.parseInt((String) jComboBox1.getSelectedItem());
        num2=Integer.parseInt((String) jComboBox2.getSelectedItem());
        sum=num1+num2;
        jTextField1.setText(" "+sum);
    }        
    }                                        

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
  {
        int num1,num2,mul;
        num1=Integer.parseInt((String) jComboBox1.getSelectedItem());
        num2=Integer.parseInt((String) jComboBox2.getSelectedItem());
        mul=num1*num2;
        jTextField1.setText(" "+mul);
  }  
    }                                        

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {                                         
 {
        int num1,num2;
        float div;
        num1=Integer.parseInt((String) jComboBox1.getSelectedItem());
        num2=Integer.parseInt((String) jComboBox2.getSelectedItem());
        div=(float)num1/num2;
        jTextField1.setText(" "+div);
    }      
    }                                        

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {                                         
 {
        System.exit(0);
    }        
    }                                        


    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JComboBox jComboBox2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration                   
}

1 个答案:

答案 0 :(得分:0)

我相信它就像这样简单:

nameOfComboBox.getSelectedItem();

如果您在从组合框中选择任何项目时询问如何控制事件,请使用以下代码(这是我的工作方式):

nameOfComboBox.addActionListener(e->nameOfMethodToHandleEvent());

然后只需创建此方法:

 nameOfMethodToHandleEvent()

并在方法中选择新项目后,将您希望发生的事情。