mabe02 / lanterna

Java library for creating text-based GUIs
GNU Lesser General Public License v3.0
2.24k stars 243 forks source link

Allow easily styling table cells #465

Open keithkml opened 4 years ago

keithkml commented 4 years ago

Right now, if you want to display one column in a different color, you need to create your own TableCellRenderer. I found myself copying and pasting code from DefaultTableCellRenderer. It would be nice if there was a simple way to style a whole cell. For example (rough sketch):

class StyledString {
    String text;
    StyleSet.Set style;
    public String toString() { return text; }
}

class StyledTableCellRenderer implements TableCellRenderer<StyledString> {
    @Override
    public void drawCell(
            Table<StyledString> table,
            StyledString cell,
            int columnIndex,
            int rowIndex,
            TextGUIGraphics textGUIGraphics) {
        StyleSet.Set style = cell.style;
        if (style.getBackgroundColor() != null) {
            textGUIGraphics.setBackgroundColor(style.getBackgroundColor());
        }
        if (style.getForegroundColor() != null) {
            textGUIGraphics.setForegroundColor(style.getForegroundColor());
        }
        textGUIGraphics.enableModifiers(style.getActiveModifiers().toArray(SGR[]::new));
        textGUIGraphics.setStyleFrom(style);
        String[] lines = getContents(cell);
        int rowCount = 0;
        for (String line : lines) {
            textGUIGraphics.putString(0, rowCount++, line);
        }
mabe02 commented 4 years ago

Please have a look at my change in f896e46 and see if that helps you at all.

keithkml commented 4 years ago

That looks great! I do think Lanterna should provide some kind of styled string class, or at least a string with a single style attached as I suggested. But your changes to the cell renderer make it much simpler to implement on my own so that’s cool.