且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JTable更改列字体

更新时间:2023-12-04 14:19:22

在JTable核心中,您基本上需要一个自定义渲染器,该渲染器将Font设置为与表字体f.i不同的东西.在DefaultTableCellRenderer的子类中.请注意,实例化后在DefaultTableCellRenderer上设置一次字体将不起作用,因为在每次调用getTableCellRendererComponent时都会重置该字体.

In core JTable you basically need a custom renderer which sets the Font to something different from the table's font, f.i. in a subclass of DefaultTableCellRenderer. Note that setting the font on DefaultTableCellRenderer once after instantiation won't work because it's reset on each call to getTableCellRendererComponent.

JTable table = new JTable(new AncientSwingTeam());
// the default renderer uses the table's font,
// so set it as appropriate
table.setFont(fontToUseForAllColumnsExceptFirst);
// a custom renderer which uses a special font
DefaultTableCellRenderer r = new DefaultTableCellRenderer() {
    Font font = fontToUseForFirstColumn;

    @Override
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus,
            int row, int column) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                row, column);
        setFont(font);
        return this;
    }

};
// doesn't work because the default renderer's font is reset
// to the table's font always
// r.setFont(font);
// set the custom renderer for first column
table.getColumnModel().getColumn(0).setCellRenderer(r);

另一种方法是在SwingX项目中支持的渲染器修饰方法(让我无法抗拒:-),那么上面的方法将是两层的(假设表的类型为JXTable):

An alternative is the renderer decoration approach, supported in the SwingX project (biased me can't resist :-) Then the above would be a two-liner (assuming table is of type JXTable):

Highlighter hl = new FontHighlighter(font);
table.getColumnExt(0).setHighlighter(hl);