private static void drawSelection(JTable table, int column, Graphics g, final int width) { int y = 0; final int[] rows = table.getSelectedRows(); final int height = table.getRowHeight(); for (int row : rows) { final TableCellRenderer renderer = table.getCellRenderer(row, column); final Component component = renderer.getTableCellRendererComponent( table, table.getValueAt(row, column), false, false, row, column); g.translate(0, y); component.setBounds(0, 0, width, height); boolean wasOpaque = false; if (component instanceof JComponent) { final JComponent j = (JComponent) component; if (j.isOpaque()) wasOpaque = true; j.setOpaque(false); } component.paint(g); if (wasOpaque) { ((JComponent) component).setOpaque(true); } y += height; g.translate(0, -y); } }
// This method from http://www.exampledepot.com/egs/javax.swing.table/PackCol.html public int packColumn(JTable table, int vColIndex, int margin) { DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel(); TableColumn col = colModel.getColumn(vColIndex); int width = 0; // Get width of column header TableCellRenderer renderer = col.getHeaderRenderer(); if (renderer == null) { renderer = table.getTableHeader().getDefaultRenderer(); } Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0, 0); width = comp.getPreferredSize().width; // Get maximum width of column data for (int r = 0; r < table.getRowCount(); r++) { renderer = table.getCellRenderer(r, vColIndex); comp = renderer.getTableCellRendererComponent( table, table.getValueAt(r, vColIndex), false, false, r, vColIndex); width = Math.max(width, comp.getPreferredSize().width); } // Add margin width += 2 * margin; // Set the width col.setPreferredWidth(width); return width; }
/** * This method gets the width of a cell, specified by a column and row number. * * @param row The column number. * @param column The row number. * @return The width of the cell data. */ private int getCellDataWidth(int row, int column) { // Inovke the renderer for the cell to calculate the preferred width TableCellRenderer cellRenderer = table.getCellRenderer(row, column); Component c = table.prepareRenderer(cellRenderer, row, column); int width = c.getPreferredSize().width + table.getIntercellSpacing().width; return width; }
private int getColumnCellWidth(JTable table, int colIndex) { int width = 0; for (int r = 0; r < table.getRowCount(); r++) { TableCellRenderer renderer = table.getCellRenderer(r, colIndex); Component comp = renderer.getTableCellRendererComponent( table, table.getValueAt(r, colIndex), false, false, r, colIndex); width = Math.max(width, comp.getPreferredSize().width); } return width; }