java - 如何从 JComboBox 中的选定项目中提取特定信息?
问题描述
我有一个具有 ComboBox 的表单,它从数据库中获取其项目。组合框从数据库内的表中获取大量列项。我只想取其中一项(从组合框中)并将其复制到 JTextField。
下面是在 Order.java 文件中创建 ComboBox 的代码:
cbinv = new JComboBox<>();
cbinv.setModel(new InvComboModel(con));
以及来自 InvComboModel.java 的代码:
public InvComboModel(Connection con) {
try {
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
String query = "SELECT * FROM inventory";
rs = stmt.executeQuery(query);
} catch (SQLException e) {
System.out.println("InvComboModel: " + e.getMessage());
}
}
@Override
public String getElementAt(int index) {
String lstn = null;
try {
rs.absolute(index + 1);
lstn = rs.getString("category") + ", " + rs.getString("description") + ", "
+ rs.getInt("price") + ", " + rs.getInt("quantity");
} catch (SQLException e) {
System.out.println("getElementAt(): " + e.getMessage());
}
return lstn;
}
@Override
public int getSize() {
int cnt = 0;
try {
rs.last();
cnt = rs.getRow();
} catch (SQLException ex) {
System.out.println("getSize(): " + ex.getMessage());
}
return cnt;
}
public int getIdInvAt(int index) {
int idInv = 0;
try {
rs.absolute(index + 1);
idInv = rs.getInt("idinv");
} catch (SQLException e) {
System.out.println("getElementAt(): " + e.getMessage());
}
return idInv;
}
因此,当我在 Inventory Item 上选择某些内容时,我希望获取第三个值(在本例中为 500,示例图像)并将其复制到 ItemPrice 的 JTextField。
[示例][1]:https://i.stack.imgur.com/BWQVw.jpg
在 Order.java 文件中,我有以下命令,但它会复制组合框中的所有选定项:
tip.setText((String) cbinv.getSelectedItem());
当我使用以下命令时,它会再次占用整行。看来我不能使用 InvComboModel.java 文件中的任何其他方法
tip.setText((String) cbinv.getModel().getElementAt());
提前致谢。
解决方案
推荐阅读
- google-sheets - 计算至少找到一次指定值的行数
- scala - 写入 csv 输出或 parquet 输出,通过配置设置控制
- r - 将列表列表转换为数据框
- javascript - 如何向刀片 Laravel json response() 显示验证消息
- json - 当你把它拿出来而不是把它带进来时,用 JSON 进行通信的标准是什么?
- arrays - Swift:CustomStringConvertible 数组数组,还有其他方法吗?
- c# - 正确的正则表达式将值放入 URL
- html - 对象 youtube 嵌入在 Firefox 中不起作用
- python - 当在循环中进行预测时,模型给出不同的分数 VS 当从模型列表中进行预测时
- java - 如何在关系的多方面使用复合主键在关系的多方面持久化数据