2

我正在尝试实现一个 Swing JTable。我按照http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#simple上的教程

我希望表格单元格不可编辑(这可行),并且我希望表格单元格的边框有更多填充。就像 HTML 中的单元格填充一样。

这是我的代码的一部分,cellpadding 不起作用。

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放在一个JScrollPane. 显示表格,单元格不可编辑,但未应用单元格填充!

任何人都可以帮忙吗?谢谢 :)

4

1 回答 1

7

getColumnClass()(默认情况下)使用in DefaultTableModelwhich 的默认实现JTable返回Object.class。这就是BoardTableCellRenderer不使用的原因,因为您正在为带有String.class.

您可以覆盖getColumnClass. 或者在这个示例的情况下,替换:

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

和:

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

看看效果BoardTableCellRenderer

于 2013-11-13T23:57:53.903 回答