以下是您的示例代碼。它能做什麼: 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();