Add cellpadding to a Java JTable

╄→尐↘猪︶ㄣ 提交于 2020-01-04 07:46:09

问题


I'm trying to implement a Swing JTable. I followed the tuorial on http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#simple

I want the table cell's not to be editable (this works) and I want the table cells to have more padding to it's borders. Like cellpadding in HTML.

This is part of my code and the cellpadding thing doesn't work.

class BoardTableCellRenderer extends DefaultTableCellRenderer {

    private static final long serialVersionUID = 1L;

    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
        super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, col);
        setBorder(BorderFactory.createEmptyBorder(15,15,15,15));
        return this;
    }
}

String[] columnNames = {"Datei",
        "Zeile",
        "Zeichen",
        "Fehler", "test"};

Object[][] data = {
        {"Kathy", "Smith", "Snowboarding", new Integer(5), new Boolean(false)},
        {"John", "Doe", "Rowing", new Integer(3), new Boolean(true)},
        {"Sue", "Black", "Knitting", new Integer(2), new Boolean(false)},
        {"Jane", "White", "Speed reading", new Integer(20), new Boolean(true)},
        {"Joe", "Brown", "Pool", new Integer(10), new Boolean(false)}
    };

JTable table = new JTable(data, columnNames){
    private static final long serialVersionUID = -4430174981226468686L;

    @Override
    public boolean isCellEditable(int arg0, int arg1) {
        return false;
    }};

table.setAutoCreateRowSorter(true);
table.getTableHeader().setReorderingAllowed(false);
table.setDefaultRenderer(String.class, new BoardTableCellRenderer());

table is placed on a JScrollPane. The table is displayed, the cells are not editable but the cellpadding is not applied!

Can anyone help? Thanks :)


回答1:


Default implementation of getColumnClass() in DefaultTableModel which is used by JTable (by default) returns Object.class. That is the reason BoardTableCellRenderer is not used, as you're setting it up for columns with String.class.

You may override getColumnClass. Or in case of this sample, replace:

table.setDefaultRenderer(String.class, new BoardTableCellRenderer());

with:

table.setDefaultRenderer(Object.class, new BoardTableCellRenderer());

to see the effect of BoardTableCellRenderer.



来源:https://stackoverflow.com/questions/19966326/add-cellpadding-to-a-java-jtable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!