Saturday, 5 September 2015

Filled Under:

How To Add Or Remove Row From JTable In Java

To manage data of a jtable first we need to create a model for a that table but if we did not create model for a table default table model will automatically created.So in this tutorial we will add and remove rows of  table using default table model the main method of this program is defined below.

addRow( rowData):

In this example I have used this method for adding row in table it will add new in last position it will add empty row until data is to be defined.

removeRow(int rownumber):

This method is used to remove row from specific position define by the user.

CODING:

import javax.swing.*; import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
class myjframe1 extends JFrame implements ActionListener
{
JTextField t1;
JTextField t2;
JButton b1,b2;
JLabel l1,l2;
JTable table;
int count,count1 = 0;
Object rowData[][];
DefaultTableModel model;
public myjframe1()
{
setTitle("J Table");
setDefaultCloseOperation(EXIT_ON_CLOSE);      
String columnNames[] = {"FIRST NAME","LAST NAME"};
    model = new DefaultTableModel(rowData, columnNames);
table = new JTable(model);
setLayout(new FlowLayout(FlowLayout.CENTER));
JScrollPane js = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
js.setPreferredSize(new Dimension(400,300));
table.setFillsViewportHeight(true);
t1 = new JTextField(12);
t2 = new JTextField(12);
b1 = new JButton("ADD");
b2 = new JButton("Remove");
l1 = new JLabel("ENTER FIRST NAME");
l2 = new JLabel("ENTER LAST NAME");
add(l1);
add(t1);
add(l2);
add(t2);
add(b1);
add(b2);
add(js);
b1.addActionListener(this);
b1.setActionCommand("add");
b2.addActionListener(this);
b2.setActionCommand("remove");
setSize(700,600);
setVisible(true);

}
public void actionPerformed(ActionEvent ae){
if ("add".equals(ae.getActionCommand()))
{
    model = (DefaultTableModel) table.getModel();
String get1 = t1.getText();
String get2 = t2.getText();
 model.addRow(new Object[]{get1,get2});
}

 
else if("remove".equals(ae.getActionCommand()))
{
   model = (DefaultTableModel) table.getModel();
    model.removeRow(table.getSelectedRow());
}
}
}
class projava
{
public static void main(String args[])
{
myjframe1 x= new myjframe1();
}
}



OUTPUT:


0 comments:

Post a Comment