establecer un valor prototipo (para el cálculo del ancho automático) de una columna JTable

StackOverflow https://stackoverflow.com/questions/838095

Pregunta

o esto no existe, o no estoy pensando / buscando correctamente porque es tarde ...

Quiero establecer un ancho de columna JTable en Swing basado en un valor de prototipo para la cadena más grande que espero (o sé) que exista en una columna en particular. No sé el número de píxeles, ya que no necesariamente conozco la fuente en tiempo de compilación.

¿Hay alguna manera de establecer un valor de prototipo para propósitos de ancho de columna, de la misma manera que existe para propósitos de altura de fila? Si es así, ¿cómo?

¿Fue útil?

Solución

¿Has intentado crear un JLabel en tiempo de ejecución y usar su tamaño para cambiar el tamaño de tu tabla?

// create a label that will be using the run-time font
JLabel prototypeLabel = new JLabel("Not Applicable")

// get the labels preferred sizes
int preferredWidth = prototypeLabel.getPreferredSize().getWidth();
int preferredHeight = prototypeLabel.getPreferredSize().getHeight();

// set the sizes of the table's row and columns
myTable.setRowHeight(preferredHeight);

for(TableColumn column : myTable.getColumnModel.getColumns()){
   column.setPreferredWidth(preferredWidth);        
}

Otros consejos

Puedes probar el siguiente código:

/**
 * Sets the preferred width of the columns of a table from prototypes
 * @param table the target table
 * @param prototypes an array of prototypes, {@code null} values will be ignored
 * @param setMaxWidth {@code true} if the maximum column width should also be set
 */
public static void setWidthFromPrototype(JTable table, Object[] prototypes, boolean setMaxWidth) {
if (prototypes.length != table.getColumnCount())
  throw new IllegalArgumentException("The prototypes array should contain exactly one element per table column");
for (int i = 0; i < prototypes.length; i++) {
    if (prototypes[i] != null) {
        Component proto = table.getCellRenderer(0,i)
                .getTableCellRendererComponent(table, prototypes[i], false, false, 0, i);
        int prefWidth = (int) proto.getPreferredSize().getWidth() + 1;
        table.getColumnModel().getColumn(i).setPreferredWidth(prefWidth);
        if (setMaxWidth)
            table.getColumnModel().getColumn(i).setMaxWidth(prefWidth);
    }
}
}

SwingX extendido JXTable / Soporte de columnas para la configuración de prototipos para el tamaño inicial del ancho de columna, puede hacerlo después de las columnas han sido creados

for(int col = 0; ....) {
    table.getColumnExt(col).setPrototypeValue(myPrototype[col]
}

o implementando una ColumnFactory personalizada que configura las columnas en la creación

ColumnFactory factory = new ColumnFactory() {
    @Override
    protected void configureTableColumn(TableModel model, TableColumnExt columnExt) {
        super(...);
        columnExt.setPrototypeValue(myPrototype[columnExt.getModelIndex()];
    }
}
table.setColumnFactory(factory);
table.setModel(myModel);

En lugar de crear una etiqueta, obtenga el componente real de TableCellRenderer y pruebe el tamaño:

// create the component that will be used to render the cell
Comp prototype = table.getDefaultRenderer(model.getColumnClass(i)).getTableCellRendererComponent(table, "Not Applicable", false, false, 0, i);

// get the labels preferred sizes
int preferredWidth = comp.getPreferredSize().getWidth();
int preferredHeight = comp.getPreferredSize().getHeight();

Este es un ejemplo de una sola columna, deberá repetir esto para obtener el tamaño de cada columna (y también configurarlo). Consulte http://www.exampledepot.com/egs/javax.swing .table / PackCol.html para ver un ejemplo de esto.

Si no conoce la fuente en tiempo de compilación, el ancho de cualquier columna JTable siempre será desconocido. Como comprobación de cordura, abra un documento de texto y juegue con diferentes fuentes mientras mantiene constante el tamaño del punto. La longitud de lo que está escrito varía según la fuente, pero la altura no lo hace.

La altura de una fila JTable debe poder determinarse para cualquier tamaño de fuente (en puntos) ya que es una estándar definido . Sin embargo, podría tomar un poco de experimentación, dado que JTable probablemente da un poco de espacio entre las celdas.

Si no puede garantizar ni el tamaño de fuente ni la fuente en sí en el momento de la compilación, entonces estoy interesado en las respuestas que otras personas aportan :)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top