You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为JTable添加JDateChooser编辑器时出现尺寸比例异常问题

解决JDateChooser在JTable中尺寸失调的问题

我来帮你搞定这个头疼的尺寸问题!单独用JDateChooser好好的,一放进Swing生成的JTable就变形,大概率是因为JTable单元格的默认尺寸逻辑和JDateChooser的布局没适配上,我给你几个实用的解决方案:

1. 让编辑器组件完全适配单元格尺寸

你的编辑器类里可以在返回JDateChooser之前,强制它匹配单元格的大小,同时去掉多余的边框,让组件填满整个单元格。修改后的编辑器类如下:

public class JDateChooserCellEditor1 extends AbstractCellEditor implements TableCellEditor { 
    private JDateChooser dateChooser = new JDateChooser(); 

    // 初始化时就做好基础配置,避免重复调用
    public JDateChooserCellEditor1() {
        dateChooser.setDateFormatString("yyyy-MM-dd");
        // 去掉组件自身边框,避免和单元格边框重叠留白
        dateChooser.setBorder(BorderFactory.createEmptyBorder());
        dateChooser.getDateEditor().getUiComponent().setBorder(BorderFactory.createEmptyBorder());
        // 设置不透明,确保背景色和单元格一致
        dateChooser.setOpaque(true);
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { 
        Date date = (value instanceof Date) ? (Date) value : null;
        dateChooser.setDate(date); 

        // 让日期选择器尺寸严格匹配当前单元格
        Dimension cellSize = table.getCellRect(row, column, true).getSize();
        dateChooser.setPreferredSize(cellSize);

        // 同步选中状态的背景色,视觉更统一
        if (isSelected) {
            dateChooser.setBackground(table.getSelectionBackground());
            dateChooser.getDateEditor().getUiComponent().setBackground(table.getSelectionBackground());
        } else {
            dateChooser.setBackground(table.getBackground());
            dateChooser.getDateEditor().getUiComponent().setBackground(table.getBackground());
        }

        return dateChooser;
    }

    @Override
    public Object getCellEditorValue() { 
        return dateChooser.getDate();
    }
}

2. 提前设置JTable的行高适配JDateChooser

JTable默认行高可能比JDateChooser的首选高度小,导致组件被压缩。初始化JTable后可以直接设置行高:

// 临时创建一个实例获取合适高度
JDateChooser tempChooser = new JDateChooser();
table.setRowHeight(tempChooser.getPreferredSize().height);

3. 检查JTable的自动列宽设置

如果你的Swing生成的JTable开启了自动调整列宽(比如table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS)),可能会压缩列宽挤压JDateChooser。可以手动调整对应列的宽度:

// 假设日期列是第2列(索引从0开始)
table.getColumnModel().getColumn(1).setPreferredWidth(120);

这样调整后,JDateChooser应该就能在JTable里正常显示,尺寸和单元格完美匹配啦!

内容的提问来源于stack exchange,提问作者Sashok

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 20:48:01