Pesquisar e mostrar (jTable)

1 resposta
D

Olá pessoal estou fazendo uma pesquisa na minha tabela esta funcionando certinho;

for (int i = 0; i < tdm.getRowCount(); i++) {
            for (int j = 0; j < tdm.getColumnCount(); j++) {
                if (tdm.getValueAt(i, j).equals(nome)) {
                    a = i;
                    b = j;
                    jTable1.clearSelection();
                    jTable1.addRowSelectionInterval(a, a);
                    jTable1.setColumnSelectionInterval(j, j);
                    jTable1.setSelectionForeground(Color.WHITE);
                    jTable1.setSelectionBackground(Color.BLACK);

                }

            }
        }

O problema é que quando o item pesquisado não esta na parte visível da tabela, o usuário tem que descer pela barra lateral até encontrar a célula selecionada, não estou conseguido fazer com que além de seleciona-la, ela seja mostrada…pesquisei a opção requestFocus() mas acho que não é isso…
Muito Obrigado.

1 Resposta

R

Segue código para tornar visível uma célula de uma JTable. O método de interesse é scrollTableToVisible():

public static void setViewportPosition(JViewport viewport,
    Rectangle newPosition) {
  // The location of the viewport relative to the object
  Point viewPosition = viewport.getViewPosition();

  // Translate the cell location so that it is relative
  // to the view, assuming the northwest corner of the
  // view is (0,0)
  newPosition.setLocation(
    newPosition.x - viewPosition.x,
    newPosition.y - viewPosition.y);

  // Scroll the area into view
  viewport.scrollRectToVisible(newPosition);
}

public static void scrollTableToVisible(JTable table, int row, int column) {
  Container parent = table.getParent();

  if (!(parent instanceof JViewport)) {
    return;
  }

  setViewportPosition((JViewport) parent,
    table.getCellRect(row, column, true));
}

Créditos pelos métodos: http://www.guj.com.br/java/100793-projeto-towel-autofiltro-em-jtable

Criado 1 de dezembro de 2011
Ultima resposta 1 de dez. de 2011
Respostas 1
Participantes 2