Как реализовать средство визуализации многострочного текста в JTable

Я столкнулся с той же проблемой, что и в следующем вопросе SO JTable. и я обнаружил Отображено несколько ячеек сделать эту работу. Теперь моя проблема заключается в том, что после реализации средства визуализации ячеек моя ячейка не показывает завернутые данные. У меня есть custom tableModel, и я не знаю, как вызвать datavalidator для этой модели. Может ли кто-нибудь предложить мне.

Модель моего стола:

public class KeywordTableModel extends AbstractTableModel {
    private static final long serialVersionUID = 1L;
    Logger logger = Logger.getLogger(KeywordTableModel.class.getName());
    KeywordList keywordList ;

public KeywordTableModel(KeywordList keywordList){
    this.keywordList = keywordList;
}

@Override
public int getRowCount() {
    // TODO Auto-generated method stub
    return keywordList.getKeywords().size();
}

@Override
public int getColumnCount() {
    // TODO Auto-generated method stub
    return keywordList.getTitles().length;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    // TODO Auto-generated method stub
    TypeRec objectRec = (TypeRec) keywordList.getKeywords().elementAt(rowIndex);
    return objectRec.getColumnData(columnIndex);
}

@Override
public String getColumnName(int column){
    return keywordList.getTitles()[column];
}

public void setDataValidator(){

}

}

Мой рендеринг ячеек:

/**
   * Multiline Table Cell Renderer.
   */
  public class MultiLineTableCellRenderer extends JTextArea 
    implements TableCellRenderer {
    /**
     * 
     */
Logger logger = Logger.getLogger(MultiLineTableCellRenderer.class.getName());
private static final long serialVersionUID = 1L;
private List<List<Integer>> rowColHeight = new ArrayList<List<Integer>>();

public MultiLineTableCellRenderer() {
  setLineWrap(true);
  setWrapStyleWord(true);
  setOpaque(true);
  logger.debug("inside multilinetablecellrenderer constructor");
}

public Component getTableCellRendererComponent(
    JTable table, Object value, boolean isSelected, boolean hasFocus,
    int row, int column) {
    logger.debug("inside multilinetablecellrenderer renderer");
  if (isSelected) {
    setForeground(table.getSelectionForeground());
    setBackground(table.getSelectionBackground());
  } else {
    setForeground(table.getForeground());
    setBackground(table.getBackground());
  }
  setFont(table.getFont());
  if (hasFocus) {
    setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
    if (table.isCellEditable(row, column)) {
      setForeground(UIManager.getColor("Table.focusCellForeground"));
      setBackground(UIManager.getColor("Table.focusCellBackground"));
    }
  } else {
    setBorder(new EmptyBorder(1, 2, 1, 2));
  }
  if (value != null) {
    setText(value.toString());
  } else {
    setText("");
  }
  adjustRowHeight(table, row, column);
  return this;
}

/**
 * Calculate the new preferred height for a given row, and sets the height on the table.
 */
private void adjustRowHeight(JTable table, int row, int column) {
  //The trick to get this to work properly is to set the width of the column to the
  //textarea. The reason for this is that getPreferredSize(), without a width tries
  //to place all the text in one line. By setting the size with the with of the column,
  //getPreferredSize() returnes the proper height which the row should have in
  //order to make room for the text.
  logger.debug("inside adjustRowheight method for adjusting the row height");
  int cWidth = table.getTableHeader().getColumnModel().getColumn(column).getWidth();
  setSize(new Dimension(cWidth, 1000));
  int prefH = getPreferredSize().height;
  while (rowColHeight.size() <= row) {
    rowColHeight.add(new ArrayList<Integer>(column));
  }
  List<Integer> colHeights = rowColHeight.get(row);
  while (colHeights.size() <= column) {
    colHeights.add(0);
  }
  colHeights.set(column, prefH);
  int maxH = prefH;
  for (Integer colHeight : colHeights) {
    if (colHeight > maxH) {
      maxH = colHeight;
    }
  }
  if (table.getRowHeight(row) != maxH) {
    table.setRowHeight(row, maxH);
  }
}

}

и я устанавливаю средство визуализации ячеек как

     cnr_DATA.setDefaultRenderer(String.class, new MultiLineTableCellRenderer());

Программа по-прежнему не переносит данные в несколько строк.


person Ashish    schedule 16.05.2013    source источник


Ответы (1)


В отсутствие полного примера я предполагаю, что вам нужно переопределить getColumnClass() в вашем TableModel, чтобы вернуть тот же тип токена, который вы указали в setDefaultRenderer(), т.е. String.class. Обратите внимание, что реализация AbstractTableModel безоговорочно возвращает Object.class.

person trashgod    schedule 17.05.2013
comment
@trashgod Большое спасибо, ваше предложение работает отлично. Еще раз спасибо - person Ashish; 18.05.2013
comment
@trashgod еще один вопрос, поэтому, если мы хотим установить ширину столбца на основе их содержимого, как мы можем этого добиться. - person Ashish; 18.05.2013