代码之家  ›  专栏  ›  技术社区  ›  Meli

Java netbeans如何将值传递给jComboBox

  •  -2
  • Meli  · 技术社区  · 9 年前

    如何将值从一个类传递到另一个类中的jcombobox

    Public void getItem (){
    try {
             dBconnection...
                  while(rs.next){
                      String customers = rs.getString (1);
    this.jcombobox1.addItem (customers);
    }
    
    }
    
    }
    

    从这个方法到另一个类中的jcombobox。错误在jcombobox中?

    2 回复  |  直到 9 年前
        1
  •  0
  •   SatyaTNV    9 年前

    因为你已经有了 B 中的类对象 A 比如说前 Bclassobj .

    Public void getItem (){
    try {
           while(rs.next){
             this.jcombobox1.addItem (rs.getString (1));
             Bclassobj.Bclassjcombobox.addItem (rs.getString (1));
         }
    
        }
       }
    
        2
  •  0
  •   STaefi Hitesh    9 年前

    一般来说,这是一种糟糕的编码方式,无意冒犯。

    您不应混合以下代码:

    1. 正在获取与数据库的连接

    2. 正在执行一些 SQL 命令并从中获取数据 ResultSet

    3. 创建图形

    只需更改方法 Public void getItem () Public List<String> getCustomers() 。该方法的业务应该只是从数据库中获取数据,并将客户姓名列表返回为 List<String> .

    然后在你的 另一个 类,只需调用此方法并设置整个 列表<字符串> 作为您的模型 JComboBox .

    请参见下面的示例:

    public class AnotherClass extends JFrame{
    
        private JComboBox<String> jComboBox;
    
        public AnotherClass() {
            init();
        }
    
        private void init(){
            //... other components
            DBClass db = new DBClass();
            List<String> customers = db.getCustomers();
            jComboBox = new JComboBox<>(customers.toArray(new String[]{}));
            this.add(jComboBox);
            //... other components
        }
    }
    
    class DBClass{
    
        public List<String> getCustomers (){
            List<String> customers = new ArrayList<>();
            try{
                 //dBconnection...
                ResultSet rs = null;// your code for getting ResultSet
                while(rs.next()){
                     String customer = rs.getString (1);
                     customers.add(customer);
                }
            }catch(SQLException e){
                e.printStackTrace();
            }
            return customers;
        }
    }
    

    祝你好运