以下代码将从文本字段中获取文本并在 JTable 中搜索它。它仅显示文本的第一次出现。我也需要连续发生。所以,请指导我如何实现这一目标。提前致谢。
private void search8()
{
String target8 = sear8.getText();
for(int row = 0; row < table8.getRowCount(); row++)
for(int col = 0; col < table8.getColumnCount(); col++)
{
String next8 = (String)table8.getValueAt(row, col);
if(next8.equals(target8))
{
showSearchResults(row, col);
return;
}
}
}
更新:
private void showSearchResults(int row, int col)
{
CustomRenderer renderer = (CustomRenderer)table8.getCellRenderer(row, col);
renderer.setTargetCell(row, col);
Rectangle r8 = table8.getCellRect(row, col, false);
table8.scrollRectToVisible(r8);
table8.repaint();
}
class CustomRenderer implements TableCellRenderer
{
public CustomRenderer()
{
label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setOpaque(true);
targetRow = -1;
targetCol = -1;
}
public Component getTableCellRendererComponent(JTable table,
Object value,boolean isSelected,boolean hasFocus,int row, int column)
{
if(isSelected)
{
label.setBackground(table.getSelectionBackground());
label.setForeground(table.getSelectionForeground());
}
else
{
label.setBackground(table.getBackground());
label.setForeground(table.getForeground());
}
if(row == targetRow && column == targetCol)
{
label.setBackground(new Color(176,196,222));
//label.setBorder(BorderFactory.createLineBorder(Color.red));
label.setFont(table.getFont().deriveFont(Font.BOLD));
}
else
{
label.setBorder(null);
label.setFont(table.getFont());
}
label.setText((String)value);
return label;
}
public void setTargetCell(int row, int col)
{
targetRow = row;
targetCol = col;
}
}