gpt4 book ai didi

java - 在JTable中实现搜索方法

转载 作者:行者123 更新时间:2023-12-01 12:52:12 25 4
gpt4 key购买 nike

我正在尝试在JTable中实现一个搜索方法,搜索代码是:

private void searchTable()
{
String id = inputIdField.getText();

for(int row = 0; row <= listAllTable.getRowCount() - 1; row++)
{
System.out.println(row);
if(id.equals(listAllTable.getValueAt(row, 0)))
{
listAllTable.scrollRectToVisible(listAllTable.getCellRect(row, 0, true));
listAllTable.setRowSelectionInterval(row, row);
for (int i = 0; i <= listAllTable.getColumnCount() - 1; i++)
{

listAllTable.getColumnModel().getColumn(i).setCellRenderer(new HighlightRenderer());
}
}
else
{

}
}
}

该方法仅在我添加字符串和对象时才有效:

final String[] columnNames = {"Name", "Surname", "Age"};

final Object[][] data = {{"Jhon", "Java", "23"}, {"Stupid", "Stupido", "500"},
{"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"},
{"Michael", "Winnie", "20"}, {"Winnie", "Thepoor", "23"}};

JTable listAllTable = new JTable(data, columnNames);

但是当我从数据库中获取数据,将其放入数组并将其显示在 JTable 中时,搜索方法不起作用,它完美地获取了行,但它没有通过 if(id.equals(listAllTable.getValueAt(row, 0)))当该值存在时,有人可以检查代码并解释为什么吗?以下是构建 JTable 的代码:

private void buildJTable(ArrayList<SalesOrder> list)
{
DefaultTableModel model = new DefaultTableModel()
{
private static final long serialVersionUID = 1L;
public boolean isCellEditable(int row, int column)
{
return false;
}
};
model.setColumnIdentifiers(new String[] {"ID", "Customer ID", "Employee ID", "Voucher ID", "Status", "Date", "Price"});
model.setRowCount(list.size());
int row = 0;
for(SalesOrder so : list)
{
model.setValueAt(so.getId(), row, 0);
model.setValueAt(so.getCustomerId().getId(), row, 1);
model.setValueAt(so.getEmployeeId().getId(), row, 2);
model.setValueAt(so.getVoucherId().getId(), row, 3);
model.setValueAt(so.getStatus(), row, 4);
model.setValueAt(so.getDate(), row, 5);
model.setValueAt(so.getPrice(), row, 6);
row++;
}
listAllTable.setRowSelectionAllowed(true);

listAllTable.setModel(model);
}

有人可以看一下代码并解释一下为什么它在从方法构建时不搜索我的 JTable private void buildJTable(ArrayList<SalesOrder> list) ?它正确构建一切,但不搜索。

谢谢。

最佳答案

您只是比较不兼容的值。尝试更改您的搜索方法如下

private void searchTable()
{
String id = inputIdField.getText();

for(int row = 0; row <= listAllTable.getRowCount() - 1; row++)
{
System.out.println(row);
String strVal = null == listAllTable.getValueAt(row, 0)? null : listAllTable.getValueAt(row, 0).toString();
if(id.equals(strVal))
{
listAllTable.scrollRectToVisible(listAllTable.getCellRect(row, 0, true));
listAllTable.setRowSelectionInterval(row, row);
for (int i = 0; i <= listAllTable.getColumnCount() - 1; i++)
{

listAllTable.getColumnModel().getColumn(i).setCellRenderer(new HighlightRenderer());
}
}
else
{

}
}
}

关于java - 在JTable中实现搜索方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24136428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com