且构网

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

JTable单元字体? (Java)

更新时间:2023-12-04 15:16:17

这就是您要寻找的内容,此代码段更改了jTable中所有列的字体. 我敢肯定,只要稍加修改,就可以解决您的情况.

for (int i = 0; i < jTable1.getColumnCount(); i ++) {
    TableColumn col = jTable1.getColumnModel().getColumn(i);
    col.setCellEditor(new MyTableCellEditor());
}


public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
    JComponent component = new JTextField();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) {
        ((JTextField)component).setText((String)value);
        ((JTextField)component).setFont(new java.awt.Font("Arial Unicode MS", 0, 12));
        return component;
    }
}

The program I am creating should work like Microsoft Excel, except in JAVA. It should also support cell formatting (Which is my problem). I have the code for detecting which cell is clicked, and what font to use working properly - I just can not figure out how to apply the Font to the cell! Google gave me CellRenderers, but it seems that cell renderers format the cell only when a condition is true. I want it to format with the specified Font it when it is called!

Can someone please help me, I am really confused!!!

I have already looked at the Java Tutorials.

My apologies if this question has been asked before!

this is what you are looking for,, this code snippet changes the font of all columns in a jTable.. I'm sure a slight modification should get your scenario covered.

for (int i = 0; i < jTable1.getColumnCount(); i ++) {
    TableColumn col = jTable1.getColumnModel().getColumn(i);
    col.setCellEditor(new MyTableCellEditor());
}


public class MyTableCellEditor extends AbstractCellEditor implements TableCellEditor {
    JComponent component = new JTextField();
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int rowIndex, int vColIndex) {
        ((JTextField)component).setText((String)value);
        ((JTextField)component).setFont(new java.awt.Font("Arial Unicode MS", 0, 12));
        return component;
    }
}