【发布时间】:2014-09-08 06:34:23
【问题描述】:
我有一个JTable,我根据数据库select 查询动态填充其列。此JTable 的一列将接受JComboBox。现在,请看下面的代码。
private class ViewClientsDisplayData extends ComponentAdapter
{
@Override
public void componentShown(ComponentEvent e)
{
dbConnector = new DBHandler();
dbConnector.makeConnection();
ResultSet rs = dbConnector.selectAllDetails("select client_id, Name from Client");
DefaultTableModel model = (DefaultTableModel) ViewClientsTable.getModel();
model.setRowCount(0);
try {
if(rs.isBeforeFirst()==false)
{
JOptionPane.showMessageDialog(null,"The table is empty");
}
else
{
try
{
while(rs.next())
{
int id = rs.getInt("client_id");
String name = rs.getString("Name");
ResultSet getPortfolios = dbConnector.selectAllDetails("select portfolio_id from Portfolio where Client_Name = '"+name+"'");
JComboBox combo = new JComboBox();
combo.removeAllItems();
while(getPortfolios.next())
{
combo.addItem(getPortfolios.getString("portfolio_id"));
}
JButton update = new JButton("Update");
JButton delete = new JButton("Delete");
JPanel btnPanel = new JPanel();
btnPanel.setLayout(new FlowLayout());
btnPanel.add(update);
btnPanel.add(delete);
Object[]row = {id, name, 0, "", new ButtonColumn(ViewClientsTable,null,"delete",4)};
model.addRow(row);
ViewClientsTable.getColumn("Portfolio").setCellEditor(new DefaultCellEditor(combo));
}
dbConnector.closeConnection();
}
catch(SQLException sqlE)
{
sqlE.printStackTrace();
JOptionPane.showMessageDialog(null,sqlE.getLocalizedMessage());
dbConnector.closeConnection();
}
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
dbConnector.selectAllDetails() 方法
public ResultSet selectAllDetails(String query)
{
ResultSet r = null;
try
{
Statement st = con.createStatement();
r = st.executeQuery(query);
}
catch(SQLException sql)
{
sql.printStackTrace();
}
return r;
}
这里的问题是我的JComboBox 没有按预期填充。它应该根据提供的搜索查询填充数据,但是,它会在所有行中显示相同的项目,即项目 03 是客户名称 AAA 的投资组合 ID em>。
下面是我的client 表(带有虚拟输入)
下面是我的Portfolio 表(带有虚拟输入)
为什么会这样?为什么JComboBox 不显示相关数据,而是重复相同的数据?
PS:我知道我们不应该根据 name 进行搜索,但我们应该从 ``unique id` 进行搜索,但这是对 SO 帖子的快速编辑。
【问题讨论】:
-
不要将组件放入模型中,您的模型应该只保存数据。列的渲染是渲染器的责任,应该单独应用于表格......
-
这里经常被问到,JDBC 没有,MadProgrammer 的评论比他的回答要好
标签: java swing jdbc jtable jcombobox