Images in JTable cells off by one pixel?

假装没事ソ 提交于 2019-12-02 01:30:34

Not entirely sure what you mean by "one pixel off" - but achieve zero intercell spacing without any visual artefacts you have to both zero the margins and turn off the grid lines:

table.setIntercellSpacing(new Dimension(0, 0)); 
table.setShowGrid(false)

Edit

Okay, looking closer, there are several issues with your code

  • you do the column sizing indirectly instead of directly (and yet another nice example why to never-ever do a component.setPreferredSize :-)
  • the renderer's border takes some size

to fix the first, configure each column's width, table layout will automagically configure its itself

    final int rows = 16;
    final int columns = 16;
    Tile tile = new Tile(0);
    int tileHeight = tile.getIcon().getIconHeight();
    int tileWidth = tile.getIcon().getIconWidth();

    JTable table = new JTable(rows, columns);
    // remove all margin
    table.setIntercellSpacing(new Dimension(0, 0));
    table.setShowGrid(false);
    table.setTableHeader(null);
    // set the rowHeight
    table.setRowHeight(tileHeight);
    // turn off auto-resize
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    // configure each column with renderer and prefWidth
    for (int j = 0; j < columns; j++) {
        TableColumn column = table.getColumnModel().getColumn(j);
        column.setCellRenderer(new MyRenderer());
        column.setPreferredWidth(tileWidth);
    }

for the second, null the border in each call:

public static class MyRenderer extends DefaultTableCellRenderer {
    @Override
    public Component getTableCellRendererComponent(JTable table,
            Object value, boolean isSelected, boolean hasFocus, int row,
            int column) {
        super.getTableCellRendererComponent(table, value, isSelected,
                hasFocus, row, column);
        setBorder(null);
        Tile tile = (Tile) value;
        setIcon(tile.getIcon());
        return this;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!