我正在构建一个自定义表格单元格编辑器,以便它在编辑期间调整行高。我有这段代码,但不是调整单元格的大小,而是调整整个面板或框架的大小。当我尝试在单元格中输入字符时,主框架宽度缩小到几个像素。 谁能看出问题所在吗?
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);
}
}
}
}
最佳答案
我关于 doLayout 的回答(可以从 CellEditor 中触发)
或者(使用 TextUtils 的更舒适方式)@kleopatra 关于 getPreferredSize 的评论
这可能(非常)让用户感到困惑,
因为我想念 JScrollPane,所以必须覆盖 MaxSize,最大尺寸是 JScrollPane 的高度和重量,否则 CellEditor 的一部分可能会超出屏幕范围........,
不要这样做,将 JScrollPane 与 JTextComponents 放在一起,覆盖 CellEditor 的 PreferredSize,
我的观点,一切都是错的,
- 使用 JTextComponent 创建应用程序模态弹出窗口(仅基于 JDialog,因为 JWindow 不允许输入到 JTextComponent),实现 ESC 键的 KeyBindings,对于 JDialog 丢失的 Fucus 也是如此,然后可以毫无问题地取消装饰
放在那里保存JButton
“保存”按钮的输出重定向到所选单元格,您不能从 JTable 内的应用程序模式中失去焦点
内容应该针对 JTable 中的所有单元格进行格式化、过滤和修改一个 JDialog
关于java - 表格单元格编辑器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12894244/