我正在構建自定義表格單元格編輯器,以便在編輯過程中調整行高度。我有這個代碼,但不是調整單元格的大小,而是調整整個面板或框架的大小。當我嘗試在單元格中輸入字符時,主框架寬度會縮小爲幾個像素。 任何人都可以看到問題嗎?表格單元格編輯器問題
class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
MyTextpane component = new MyTextpane();
MyTable table;
private int row;
private int col;
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected,
int rowIndex, int vColIndex) {
((MyTextpane) component).setText((String) value);
component.addKeyListener(new KeyListener1());
this.table =(MyTable) table;
this.row = rowIndex;
this.col = vColIndex;
return component;
}
public Object getCellEditorValue() {
return ((MyTextpane) component).getText();
}
public class KeyListener1 implements KeyListener {
@Override
public void keyTyped(KeyEvent ke) {
}
@Override
public void keyPressed(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
adjustRowHeight(table, row, col);
}
private java.util.List<java.util.List<Integer>> rowColHeight = new ArrayList<java.util.List<Integer>>();
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.
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));
}
java.util.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);
}
}
}
}
爲了更快地獲得更好的幫助,請發佈[SSCCE](http://sscce.org/)。 –
只有DocumentListener可以強制Document,PlainDocument返回座標,KeyListener是非生產性的,簡單無用,如果你想過濾un_:想要的字符放在那裏DocumentFilter代替DocumentListener並覆蓋通知到文檔:-) – mKorbel
hmm ..不能在容器層次結構中重現縮小範圍(使用帶有JTextArea的編輯器而不是JTextPane,而不是懶惰:匹配自定義渲染器)。但即便如此,這種行爲還遠沒有達到最佳狀態,因爲在編輯時編輯器的大小發生了不可預測的變化。實際上,我懷疑動態改變行高的同時打字可以在不進行大量調整的情況下實現。 – kleopatra