Domanda

I use my JTable, my JTableModel for my project. I can not start the table with my column headers and empty data. May you help me? Thank you. Here is my code

MainCode class

  public class MainCode extends JFrame{
       public MainCode(){
  ...........other codes here........
  MyTableModel tm= new MyTableModel();
  MyTable table=new MyTable(tm);
  //JTable table=new JTable(tm); if I write this line,I see column names.
  table.setPreferredScrollableViewportSize(new Dimension(480,80));
  table.setFillsViewportHeight(true);
  JScrollPane scrollPanetable=new JScrollPane(table);
  frame.getContentPane().add(scrollPanetable)
  ........another codes...........  

 }
}

MyTable class

public class MyTable extends JTable{
public MyTable(){

}
public MyTable(int row,int col){
    super(row,col);
}
@Override
public void tableChanged(TableModelEvent e){
    super.tableChanged(e);
    repaint();
    System.out.println("public void tableChanged(TableModelEvent e)");
}

}

MyTableModel class

public class MyTableModel extends AbstractTableModel{
   private String[] columnNames; 
   private Object[][] data;
public MyTableModel(){
    super();
    columnNames=new String[]{"A","B","C"};
    data=new Object[][]{ {null,null,null}};
}
public int getColumnCount() {
    return columnNames.length;
}

public int getRowCount() {
    return data.length;
}

public String getColumnName(int col) {
    return columnNames[col];
}

public Object getValueAt(int row, int col) {
    return data[row][col];
}
 }

it is not started with column names. What is wrong with this code.I see below image. enter image description here

È stato utile?

Soluzione

Because you do not have constructor in MyTable which takes parameter MyTableModel.

You are creating table like this:

MyTable table=new MyTable(tm);

So you must have constructor in MyTable like this:

class MyTable extends JTable {

   public MyTable(MyTableModel tm){
        super(tm);
    }
}

If you have MyTable code that you posted here, your code will not compile!

Altri suggerimenti

Why are you overriding JTable?

Your own comment, if I write this line,I see column names suggests that your overriding of JTable is the problem. You have an overridden implementation of tableChanged(...), which the docs say Application code will not use these explicitly, they are used internally by JTable. Otherwise, your subclassed JTable isn't doing anything special to warrant subclassing.

If you must subclass, you have to tell the subclass how to use your model, which you haven't done (either via a constructor or setModel(...)).

More than likely you have not added the JTable in a JScrollPane which will cause the column names to be hidden

add(new JScrollPane(table));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top