我正在构建一个自定义表格单元格编辑器,以便在编辑期间调整行高。我有这个代码,但它没有调整单元格的大小,而是调整整个面板或框架的大小。当我尝试在单元格中输入字符时,主框架宽度会缩小到几个像素。 有谁能看到这个问题?
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);
}
}
}
}
答案 0 :(得分:1)
关于doLayout的答案(可以从CellEditor中解雇)
或(超过使用TextUtils的舒适方式)@kleopatra关于getPreferredSize的评论
这可能(非常)混淆用户,
因为我想念JScrollPane,所以必须覆盖MaxSize,最大尺寸是高度&amp; JScrollPane的权重,否则CellEditor的一部分可以超出screeens边界.........,
不要那样做,把JScrollPane放到JTextComponents中,覆盖CellEditor的PreferredSize,
一切都是错的,我的观点,
放在那里Save JButton
从保存按钮输出重定向到所选单元格,您无法从JTable中的应用程序模式中失去焦点
内容应格式化,过滤,修改一个来自JTable的所有单元格的JDialog
答案 1 :(得分:1)
作为在编辑时调整行大小的替代方法,请考虑使用JTextArea
的{{3}}。