Edijae Crusar
Edijae Crusar

Reputation: 3541

How do I insert new row into a JTable using a custom table model?

I'm working on a small project that involves JTable which requires the user to click a button and add a row to the table (I have named the button as addrow). I have used a custom table model (Mytablemodel) which extends Default table model. My table is first made up of five rows and 4 columns where afterwards user can click the addrow button to add more rows

Everything in my code works fine except the addrow button which does nothing. I will appreciate any help.

public class AddingNewRows extends JFrame {
JTable mytable;
JButton addrow;
String[] columns={"Admission number","Name","School","Year"};
TableColumn tc;
int defaultrows=5;
int rows=new Mytablemodel().getRowCount(),columnscount=new Mytablemodel().getColumnCount();
List data=new ArrayList();
Mytablemodel mytbm;
//
public AddingNewRows(){
super("adding rows");
for(int initialrows=0; initialrows<5; initialrows++){
   String[] items={"1","2","3","4"};
 data.add(items);
}
mytbm=new Mytablemodel();
mytable=new JTable(mytbm);

JScrollPane scroll=new JScrollPane(mytable);
addrow=new JButton("ADD ROW");
//
JPanel buttonpanel=new JPanel();
buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.X_AXIS));
buttonpanel.setAlignmentX(Component.RIGHT_ALIGNMENT);
buttonpanel.add(addrow);

//
add(scroll,BorderLayout.CENTER);
add(buttonpanel,BorderLayout.SOUTH);

addrow.addActionListener(new Myactions());

}
public class Mytablemodel extends DefaultTableModel{

@Override
public String getColumnName(int column) {
    return columns[column];
}
@Override
public Object getValueAt(int row, int col){
 return ((String[])data.get(row))[col]; 
}
@Override
public boolean isCellEditable(int row, int col){
  return true;
}
@Override
public void setValueAt(Object value,int row, int col){
  ((Object[])data.get(row))[col]=value;
  fireTableCellUpdated(row,col);

}
@Override
public Class getColumnClass(int column){
  return getValueAt(0,column).getClass();
}  
@Override
public int getColumnCount(){
  return columns.length;
}

@Override
public int getRowCount(){
  return increaserows; 
}

@Override
public void addRow(Object[] mynewdata){
  int rownum=data.size();
  System.out.println(rownum);
  data.add(madata);
fireTableRowsInserted(rownum,rownum);
}

}
//
private class Myactions implements ActionListener{

@Override
public void actionPerformed(ActionEvent event){
 if(event.getSource()==addrow){ 
   Object[]newdata={"","","",""};
    mytbm.addRow(newdata);  
 } 
} 
}
public static void main(String[] args) {

 AddingNewRows frame=new AddingNewRows();
 frame.setVisible(true);
    frame.setSize(400,400);
    frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);

}

}

Upvotes: 0

Views: 2535

Answers (2)

Edijae Crusar
Edijae Crusar

Reputation: 3541

According to your question,You want to add new rows every time the user clicks the addrow button. Achieve your objective by using DefaultTableModel without creating your own or overriding addrow method. in my example below,parameters in the DefaultTableModel constructor represents the initial rows(5) and columns(4) that the table will have where after execution, the user can add more rows by clicking the addrow button.

public class AddingNewRows extends JFrame {
 DefaultTableModel def;
JTable mytable;
JButton addrow;
//
public AddingNewRows(){
super("adding rows");

def=new DefaultTableModel(5,4);
mytable=new JTable(def);

JScrollPane scroll=new JScrollPane(mytable);
addrow=new JButton("ADD ROW");
//
JPanel buttonpanel=new JPanel();
buttonpanel.setLayout(new BoxLayout(buttonpanel,BoxLayout.X_AXIS));
buttonpanel.add(addrow);

//
add(scroll,BorderLayout.CENTER);
add(buttonpanel,BorderLayout.SOUTH);

addrow.addActionListener(new Myactions());

}

private class Myactions implements ActionListener{

@Override
public void actionPerformed(ActionEvent event){
if(event.getSource()==addrow){ 
Object[]newdata={"","","",""};
def.addRow(newdata);
} 
} 
}
public static void main(String[] args) {
AddingNewRows frame=new AddingNewRows();
frame.setVisible(true);
frame.setSize(400,400);
frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);

}

}

Upvotes: 0

dic19
dic19

Reputation: 17971

Some notes about your code:

  • You never should call any of the fireXxx() methods explicitely from the outside. Those are intended to be called internally by AbstractTableModel subclasses when needed. Note: IMHO those should be protected and not public, to avoid use them incorrectly. But for some reason they made them public.

  • Your addrow button seems to create a new table model that is not attached to any JTable so it makes no sense. Your table model should provide an addRow(...) method in order to add a new row to it. Most likely you will have to enlarge the two-dimensions array that is the table model's underlyinig data structure any time a row is added.

  • As @AndrewThompson already suggested, DefaultTableModel seems a good match to do what your table model does.

  • Check rows and columnscount properties initialization. It doesn't seem right to me.

On the other hand, you say in a comment:

I'm having trouble understanding the fireTableRowsInserted(int,int) method. the parameters themself and where or when to call the method

This method should be called within the addRow(...) that I've suggested you to create in the second point. This method should enlarge the data structure and notify the TableModelListeners that a new row/s has/have been inserted. The parameters are the first and last indexes respectively. Tipically when you append a new single row to the end of the table model, then both first and last indexes are the same and the new size - 1 of the underlying data structure. Of course, several rows can be inserted and not necessarily at the end of the table model, so you have to figure out the appropriate indexes. See the example shown here which uses a List of custom objects as data structure.

Upvotes: 2

Related Questions