简体   繁体   中英

JTable headers doesn't set

Last two days I've been trying to create a data view table in java app with JTable .

Netbeans binding option doesn't work, but nevermind, I managed to create my own TableModel .

Data get shown in the table, but the headers always contain just letters (A, B, C... for each column). At one point everything worked well, but then I wanted to set another model for that particular table and it doesn't show the labels correctly anymore even if I create whole new JPanel and set it up from scratch.

This is my custom TableModel class

public class MyTableModel extends AbstractTableModel{    

private ArrayList<Options> list;
String[] headers;

public MyTableModel(ArrayList<Options> list, String[] headers) {
    this.list = list;
    this.headers = headers;
}


@Override
public int getRowCount() {
    return this.list.size();
}

@Override
public int getColumnCount() {
    return headers.length;
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
    if(columnIndex == 0) {
        return list.get(rowIndex).getId();
    }
    if(columnIndex == 1) {
        return list.get(rowIndex).getText();
    }
    else {
        return null;
    }
}    }

And this is part of the code in jframe class(the one which I run)

ArrayList<Options> list;
 String[] optionHeaders = {"id", "text"};

public table2frame() {

    initComponents(); 
    list = (ArrayList) zadanie_2_app.Zadanie_2_app.findAll();
    JTable table2 = new JTable(new MyTableModel(list, optionHeaders));}

AbstractTableModel requires that getColumnName be overridden otherwise placeholder column names are used. Add

@Override
public String getColumnName(int column) {
   return headers[column];
}

I wanted to set another model for that particular table and it doesn't show the labels correctly anymore even if I create whole new JPanel and set it up from scratch.

AFAIK understand from this desription, that JTable is container for JTable

  • put JTable to the JScrollPane, JTable should be placed into JScrollPane, otherwise JTableHeader isn't visible automatically

  • get JTableHeader from JTable, change LayoutManager for JPanel to BorderLayout, put JTable to CENTER area, JTableHeader to NOTHR area

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM