Как реализовать многострочное рендеринг текста в JTable
Я столкнулся с той же проблемой, о которой говорилось в следующем вопросе SO Wrap несколько строк в JTable. и я обнаружил, что Multile ячейка готова для этой работы. Теперь моя проблема заключается в том, что после реализации средства визуализации ячеек в моей ячейке не отображаются упакованные данные. У меня есть пользовательский 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());
Программа по-прежнему не переносит данные в несколько строк.
1 ответ
Решение