Question

My JTable identifiers won't show up. I have tried a lot of different things but not even a little change has come.. So now I'm asking here.

My code:

public void showTable() {
    String[] heads = {"PersonID", "Name", "Date", "Age"};

    DefaultTableModel model = new DefaultTableModel();

    model.setColumnIdentifiers(heads);
    model.setRowCount(4);

    JTable table = new JTable(model);

    int row = 2;

    table.setValueAt("Test1", row, 0);
    table.setValueAt("Test2", row, 1);
    table.setValueAt("Test3", row, 2);
    table.setValueAt("Test4", row, 3);


    mainBackgroundManager.add(table, BorderLayout.CENTER);
}

What shows up is:

I've tried to write this too but that won't work either:

public void showTable() {
    DefaultTableModel model = new DefaultTableModel();

    model.setRowCount(4);
    model.setColumnCount(4);

    JTable table = new JTable(model);

    table.getColumnModel().getColumn(0).setHeaderValue("PersonID");
    table.getColumnModel().getColumn(1).setHeaderValue("Name");
    table.getColumnModel().getColumn(2).setHeaderValue("Date");
    table.getColumnModel().getColumn(3).setHeaderValue("Age");

    int row = 2;

    table.setValueAt("Test1", row, 0);
    table.setValueAt("Test2", row, 1);
    table.setValueAt("Test3", row, 2);
    table.setValueAt("Test4", row, 3);


    mainBackgroundManager.add(table, BorderLayout.CENTER);
}

Thank you.

Was it helpful?

Solution

There are two ways for you. The more difficult one, from the JTable API:

"Note that if you wish to use a JTable in a standalone view (outside of a JScrollPane) and want the header displayed, you can get it using getTableHeader() and display it separately."

Would look something like that:

JTableHeader header = table.getTableHeader();

mainBackgroundManager.add(header, BorderLayout.NORTH);
mainBackgroundManager.add(table, BorderLayout.CENTER);

The easier one (prefered):
Put your JTable inside a JScrollPane. Try this:

mainBackgroundManager.add(new JScrollPane(table), BorderLayout.CENTER);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top