我有一个名为“supplier”的表,其中有两列“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
的模型,显然,供应商的名称是从存储您尝试添加的新供应商名称的任何变量中获取的。
如果异常阻止添加供应商,则将供应商名称添加到组合框的部分将不会运行,因为控制会立即传递到 try/catch 的 catch
部分。
当您已经拥有所需的所有数据时,在成功插入新供应商后运行无关的选择语句来重新填充组合框是没有意义的。
关于java - 使用 MySQL 中的数据填充 JComboBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61396549/