Search in This Blog

Add new row dynamically in JTable

Problem:

Add new row dynamically in JTable
This is Java code allow to you add a new row in JTable.
when you press enter then a new row automatically inserted and you can make more entry.


Add new row dynamically in JTable









Solution & Example:

import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.table.*;
public class t1 extends JFrame {
DefaultTableModel model;
JTable table;
JScrollPane sc1;
public t1() {
super("Data Entry Form By Amit Gaur (amitt800@gmail.com)");
int i,j;
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
model = new DefaultTableModel();
table = new JTable(model);
model.addColumn("Name");
model.addColumn("ID");
model.addColumn("Salary");
model.addColumn("Jobs");
model.addRow(new Object[]{"","","",""});
table.addKeyListener(new KeyListener() {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode()==KeyEvent.VK_ENTER) {
model.addRow(new Object[]{"", "","",""}); } }
public void keyReleased(KeyEvent e) { }
public void keyTyped(KeyEvent e) { } } );

sc1 = new JScrollPane(table,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); cp.add(sc1);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(600,600);
setVisible(true);
}
public static void main(String[] ss) {
new t1();
}
}




Previous
Next Post »