Java 如何从ms access中的数据库中从jcombobox添加多个项
组合框显示正确,但只显示数据库表中的一项。为什么?我如何允许多个项目从数据库放入jcombobox?还有,为什么它总是抱怨并建议抑制警告?不要使用空布局和设置边界(…)。Swing设计用于布局管理器 由于Swing组件(顶层容器除外)在默认情况下是可见的,因此不需要使用Java 如何从ms access中的数据库中从jcombobox添加多个项,java,sql,swing,ms-access,jcombobox,Java,Sql,Swing,Ms Access,Jcombobox,组合框显示正确,但只显示数据库表中的一项。为什么?我如何允许多个项目从数据库放入jcombobox?还有,为什么它总是抱怨并建议抑制警告?不要使用空布局和设置边界(…)。Swing设计用于布局管理器 由于Swing组件(顶层容器除外)在默认情况下是可见的,因此不需要使用comboBox.setVisible(true) 还有,为什么它总是抱怨并建议禁止警告 您尚未指定将添加到组合框模型的数据类型。您正在添加字符串数据,因此应使用: import java.sql.*; import java.a
comboBox.setVisible(true)
还有,为什么它总是抱怨并建议禁止警告
您尚未指定将添加到组合框模型的数据类型。您正在添加字符串数据,因此应使用:
import java.sql.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class ComboExample {
Connection con;
Statement st;
ResultSet rs;
ComboExample() {
JFrame f = new JFrame();
f.getContentPane().setLayout(null);
final JComboBox combo = new JComboBox();
try {
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:TTracking";
con = DriverManager.getConnection(db);
// Getting database info
DatabaseMetaData meta = con.getMetaData();
System.out.println("Server name: " +
meta.getDatabaseProductName());
System.out.println("Server version: " +
meta.getDatabaseProductVersion());
System.out.println("");
System.out.println("Creating statement...");
st = con.createStatement();
String sql = "SELECT Trailer FROM TrailerLocationMaster";
ResultSet rs = st.executeQuery(sql);
while (rs.next()) {
String trailer = rs.getString("Trailer");
combo.addItem(trailer);
System.out.println(rs.getString("Trailer"));
combo.setVisible(true);
}
}
catch (Exception ex) {
}
combo.setBounds(20, 50, 150, 20);
f.add(combo);
f.setSize(400, 200);
f.setVisible(true);
}
public static void main(String[] args) {
ComboExample c = new ComboExample();
}
}
JComboBox组合=新建JComboBox();
请仔细阅读以了解更多信息
如何允许数据库中的jcombobox中有多个项
你没有做什么特别的事。您的代码看起来很合理,因为您有一个while循环,并且调用了addItem(…)方法
如果您只有一项,那么我猜您的查询只返回一项。您的输出应该验证这一点。向表格中添加更多数据。不要忘记单击复选标记开始“接受”答案。你还没有接受你所有问题的一个答案。我的声誉还不足以让我接受你的回答。刚才我注意到箭头下面有一个勾号谢谢你的帮助。我的数据库中有多个值,它仍然只允许我在下拉列表中的第一条记录
JComboBox<String> combo = new JComboBox<String>();