java从组合框中获取特定值

时间:2017-09-27 16:26:05

标签: java

我是java的新手,所以我不太清楚如何在点击按钮时获得getString("id")值。现在我得到的是id和全名,但我真正想得到的是什么只是id。

 jComboBox1.addItem(rs.getString("id")+" > "+rs.getString("first_name") +" "+ rs.getString("surname"));  

jButton2.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton2ActionPerformed(evt);
            String value = (String)jComboBox1.getSelectedItem();//need to change
            jTextField1.setText(value);
        }
    });

I dun want the txtfiel show all the value, I only want to get id

1 个答案:

答案 0 :(得分:2)

  

我不知道如何存储对象和拥有属性,请你给我一个参考或链接

实际上在网上找到教程和参考资料并不困难,例如,

无论如何,这是一个如何使用它的例子:

  1. 实现一个Java对象(我们将其命名为Person),该对象应包含属性idfirst name and姓氏:

    public class Person {
        private String id;
        private String firstName;
        private String surname;
    
        public Person(String id, String fname, String sname) {
            this.id = id;
            this.firstName = fname;
            this.surname = sname;
        }
    
        public String getId() {
             return id;
        }
    
        public String getFirstName() {
            return firstName;
        }
    
        public String getSurname() {
             return surname;
        }
    
        // toString() method will be called when the ComboBox is rendered
        @Override
        public String toString() {
            return id + " > " + firstName + " " + surname;
        }
    }
    
  2. 将上述对象的实例添加到ComboBox中:

    jComboBox1.addItem(new Person(rs.getString("id"), rs.getString("first_name"), rs.getString("surname")));
    
  3. 并将动作侦听器修改为:

    new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
        jButton2ActionPerformed(evt);
        Person value = (Person)jComboBox1.getSelectedItem();
        jTextField1.setText(value.getId());
    }