以下是您的示例代码。它能做什么: 1)创建一个组合框 2)建立从类型DemoModelItem的项目(尝试注释掉overrided toString方法) 3)组合框模型设置组合框模型
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
class DemoModelItem {
public String objectName;
public String objectType;
public DemoModelItem(String objectName,String objectType){
this.objectName = objectName;
this.objectType = objectType;
}
public String toString(){
return objectType+"-"+objectName;
}
}
public class ComboTest {
public static Connection getConnection() throws Exception {
Connection conn = null;
//open connection
return conn;
}
public static DefaultComboBoxModel buildComboBoxModel() throws Exception {
DefaultComboBoxModel comboBoxModel = new DefaultComboBoxModel();
String SQL = "SELECT object_name, object_type from some_table";
Connection c = null;
try {
c = getConnection();
PreparedStatement ps = c.prepareStatement(SQL);
ResultSet rs = ps.executeQuery();
while(rs.next()){
comboBoxModel.addElement(new DemoModelItem(rs.getString("OBJECT_NAME"),rs.getString("OBJECT_TYPE")));
}
rs.close();
ps.close();
} catch (Exception e) {
throw e;
}finally{
try{c.close();}catch(Exception e){;}
}
return comboBoxModel;
}
public static void main(String[] args) throws Exception {
JComboBox comboBox = new JComboBox();
comboBox.setModel(buildComboBoxModel());
JFrame frame = new JFrame("Combo Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(comboBox);
frame.pack();
frame.setVisible(true);
}
}
在这里,而不是使用 模型.addElement()尝试使用JcomboBox.addItem();