我有一个名为“ 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语句,然后将其存储在字符串中,但是当我插入数据时,我将不得不不断添加更多字符串以容纳额外的信息。
答案 0 :(得分:0)
我不知道如何创建组合框,因为您忽略了发布代码,但是总之,要在每次添加新供应商时都保持组合框的更新,可以使用以下逻辑(实际实现由您决定) ):
在您的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
部分。
在已经拥有所需的所有数据之后,成功插入新的供应商之后,运行无关的select语句来重新填充组合框是没有意义的。