我有一个具有 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());
提前致谢。