for (String[] cells : rows) { if (maxWidths == null) { maxWidths = new int[cells.length]; } if (cells.length != maxWidths.length) { throw new IllegalArgumentException("Number of row-cells and headers should be consistent"); } for (int i = 0; i < cells.length; i++) { maxWidths[i] = Math.max(maxWidths[i], cells[i].length()); } }
if (headers != null) { printLine(maxWidths); printRow(headers, maxWidths); printLine(maxWidths); } for (String[] cells : rows) { printRow(cells, maxWidths); } if (headers != null) { printLine(maxWidths); } }
private void printLine(int[] columnWidths) { for (int i = 0; i < columnWidths.length; i++) { String line = String.join("", Collections.nCopies(columnWidths[i] + verticalSep.length() + 1, HORIZONTAL_SEP)); System.out.print(joinSep + line + (i == columnWidths.length - 1 ? joinSep : "")); } System.out.println(); }
public static void main(String[] args) { //test code CommandLineTable st = new CommandLineTable(); //st.setRightAlign(true);//if true then cell text is right aligned st.setShowVerticalLines(true);//if false (default) then no vertical lines are shown st.setHeaders("one", "two", "three");//optional - if not used then there will be no header and horizontal lines st.addRow("super", "broccoli", "flexible"); st.addRow("assumption", "announcement", "reflection"); st.addRow("logic", "pleasant", "wild"); st.print(); } }
Output
+------------+--------------+------------+ | one | two | three | +------------+--------------+------------+ | super | broccoli | flexible | | assumption | announcement | reflection | | logic | pleasant | wild | +------------+--------------+------------+