• Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.
    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Java How can i define table width?

newbie

New Coder
I create cells from the list size and trying to set width fist 1 only number 2nd is name and next others will be only number which means i need 2nd line more spaced and others are same width. Sorry my english
 

Ghost

Active Coder
This example isnt for Java, but covers a lot of the same iText concepts

Code:
PdfPTable table = new PdfPTable(3);
PdfPCell cell = new PdfPCell(new Phrase("Header spanning 3 columns"));
cell.Colspan = 3;
cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
table.AddCell(cell);
table.AddCell("Col 1 Row 1");
table.AddCell("Col 2 Row 1");
table.AddCell("Col 3 Row 1");
table.AddCell("Col 1 Row 2");
table.AddCell("Col 2 Row 2");
table.AddCell("Col 3 Row 2");
doc.Add(table);

Here is an example I found online for iText Sharp

What version of iText are you using ??
 

YNW_Kyle

New Coder
Use this method:

Java:
public static void setColumnWidths(JTable table, int... widths) {

    TableColumnModel columnModel = table.getColumnModel();

    for (int i = 0; i < widths.length; i++) {

        if (i < columnModel.getColumnCount()) {

            columnModel.getColumn(i).setMaxWidth(widths);

        }

        else break;

    }

Or extend the JTable class:

Java:
public class Table extends JTable {

    public void setColumnWidths(int... widths) {

        for (int i = 0; i < widths.length; i++) {

            if (i < columnModel.getColumnCount()) {

                columnModel.getColumn(i).setMaxWidth(widths);

            }

            else break;

        }

    }

}

And then:

table.setColumnWidths(30, 150, 100, 100);
 
Last edited by a moderator:
Top Bottom