java - 使用来自 MySQL 的数据填充 JComboBox
问题描述
我有一个名为“供应商”的表,它有两列“suppID”和“suppName”。
我想从 suppName 中提取数据并将其填充到 JComboBox 中,以使内容保持最新,这意味着如果插入或删除了新行,JComboBox 将完全按照它存储在表中的数据显示打开它的时间
addStock.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae) {
int result = JOptionPane.showConfirmDialog(null,addStockPanel,"Add new stock", JOptionPane.OK_CANCEL_OPTION);
try{
//Connect to DB
Connection conn = CatalogueDB.getConnection();
//Prepare statement to pull data
Statement pull = conn.createStatement();
} catch(Exception e){System.out.println("Error adding supplier");}
//Finish by printing a message to say the insert has worked.
finally{
System.out.println("Insert Completed.");
以我的知识水平想到的唯一想法是从表中执行一个 select 语句,然后将其存储在一个字符串中,但是当我插入数据时,我将不断地添加更多字符串以容纳额外的信息。
解决方案
我不知道您是如何创建组合框的,因为您忽略了发布代码,但简而言之,要在每次添加新供应商时更新组合框,您可以使用以下逻辑(实际实现取决于您):
在您的 try 语句中(您实际上是在尝试将新供应商添加到您的表中),遵循 SQL 语句的执行,如下所示:
try
{
//Connect to DB
Connection conn = CatalogueDB.getConnection();
//Prepare statement to push new supplier data
Statement push = conn.createStatement();
// adds new supplier name
model.addElement(<name of supplier>);
// notifies combobox that the underlying model has changed
// box will be repainted automatically
model.fireContentsChanged();
}
catch(Exception e)
{
e.printStackTrace();
// other handling as necessary
}
model
用于您的模型在哪里JComboBox
,显然,供应商的名称是从存储您尝试添加的新供应商名称的任何变量中获得的。
如果异常阻止添加供应商,则将供应商名称添加到组合框中的部分将不会运行,因为控制会立即传递到catch
您的 try/catch 部分。
当您已经拥有所需的所有数据时,在成功插入新供应商后运行无关的选择语句来重新填充组合框是没有意义的。
推荐阅读
- python - 使用reduce连接多个数据框,其中一个为空
- react-native - 组件未在 headerTitle 中呈现
- macos - 如何在 MAC OS 上使用 QML 构建应用程序?
- php - 如何修复错误 spl_autoload_register():Argument has been ignored
- r - shinyapp 中的绘图对输入没有反应
- c# - 如何在 EF Core 中禁止默认值?
- linux - 如何查找目录中多个文件的数量和总大小?
- node.js - NodeJS nodejavabridge 在工作线程中初始化时抛出错误
- python - 如何解决 TypeError:在 Jupyter notebook 中使用 numpy 规范化数据时,'tuple' 对象不能被解释为整数
- matlab - Spider_plot 在 matlab 应用程序设计器中不起作用