我有一个 JTable。我已经在这样的方法中添加了该列。
private void createSearchResultTable() {
DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
String columnNames[] = {"Title", "Author", "Edition", "Availability", "Reserve"};
for (int i = 0; i < columnNames.length; i++) {
TableColumn column = new TableColumn();
column.setHeaderValue(columnNames[i]);
columnModel.addColumn(column);
}
tblBookSearchResults.setColumnModel(columnModel);
ButtonColumn buttonColumn = new ButtonColumn(tblBookSearchResults, reserveBook, 4);
buttonColumn.setMnemonic(KeyEvent.VK_ENTER);
}
现在我用从 MySQL 数据库中检索到的数据填充 JTable。
private boolean populateSearchResultTable(String title, String author, String publisher) {
con = DatabaseHandler.connectToDb();
try {
if (title.trim().length() != 0) {
pst = con.prepareStatement("SELECT title, author, edition, status FROM book WHERE title LIKE ? ");
pst.setString(1, "%" + title + "%");
}
else if (author.trim().length() != 0) {
// Say, this query is getting executed
pst = con.prepareStatement("SELECT title, author, edition, status FROM book WHERE author LIKE ? ");
//pst.setString(1, "%" + author + "%");
pst.setString(1, "Dan");
}
else if (publisher.trim().length() != 0) {
pst = con.prepareStatement("SELECT title, author, edition, status FROM book WHERE publisher LIKE ? ");
pst.setString(1, "%" + publisher + "%");
}
rs = pst.executeQuery();
int rowNum = 0;
while (rs.next()) {
tblBookSearchResults.setValueAt(rs.getString(1), rowNum, 1);
}
return true;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getLocalizedMessage());
}
finally {
}
return false;
}
检索数据集没有问题,但是当我将值设置为 JTable 时,它看起来像这样。
第一个值在所有列中重复。我不明白为什么会这样?任何有关如何纠正此问题的建议将不胜感激。
谢谢你。