Sunday, 26 May 2013

Dynamically add a row to JTable in Java on press of Enter Button

On task that a swing programmer faces often is to add a new Row dynamically to the JTable on press of an Enter Button . So lets understand a simple solution to this problem .

Here's our  code (A solution to add a row dynamically o our JTable on press of an Enter Button):-

package jtables;

/**
 *
 * @author Pramod . Choudhari || http://techwayz.com
 */

import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;

class BuildFrame{

    private JFrame jf;
    private JScrollPane js;
    private JTable jt;
    private DefaultTableModel mod;
    private static int i=0;
    public BuildFrame() {
        System.out.println("Constructor called");
        jf = new JFrame("JTable Example #1");
        js = new JScrollPane();
        jt = new JTable();
        mod = new DefaultTableModel() {

            @Override
            public int getColumnCount() {
                return 3;
            }

            @Override
            public String getColumnName(int column) {
                switch (column) {
                    case 0:
                        return "No";
                    case 1:
                        return "Name";
                    case 2:
                        return "Age";
                    default:
                        return "Unknown";
                }
            }
        };
        jt.setModel(mod);
        jf.setSize(400, 300);
        jf.setResizable(false);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        jf.setLocation(200, 300);
        jf.add(js);
        js.setViewportView(jt);
        // add a Dummy row to our JTsable
        mod.addRow(new Object[]{"1","Pramod","24"});
        jt.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtKeyPressed(evt);
            }
        });
        jf.setVisible(true);
    }
    
   private void jtKeyPressed(java.awt.event.KeyEvent evt) {
        i = Integer.parseInt(mod.getValueAt(mod.getRowCount() - 1, 0).toString());
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            i++;
            mod.addRow(new Object[]{String.valueOf(i)," "," "});
        }
    }
}
   

public class JTables {

    public static void main(String[] args) {
        // TODO code application logic here
        BuildFrame bf = new BuildFrame();
    }
}


Screenshot (After running the above code i pressed the enter key 6 times hence the row count is 7 )





Description :-
  • Default constructor of the class BuildFrame would be called on executing the above code .
  • The default Constructor of the class BuildFrame has the role of generating our Swing Components JFrame,JTable … etc .
  • To detect enter key presss , we would be using KeyListener in our code …so that We can add a new row to our existing JTable on KeyPressed Event .

Have a look at these lines of code :-

jt.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jtKeyPressed(evt);
            }
        });

  • In the first line we are adding a KeyListener to our JTable ..
  • Now in the second line , we’re overriding keyPressed(KeyEvent evt) method .
  • In the Third line ,  the method [  jtKeyPressed(evt);  ]containing the code to handle the event i.e code to add a new row dynamically to the JTable is called .


Lets look at the body of the method being called in the third line .
private void jtKeyPressed(java.awt.event.KeyEvent evt) {
        i = Integer.parseInt(mod.getValueAt(mod.getRowCount() - 1, 0).toString());
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            i++;
            mod.addRow(new Object[]{String.valueOf(i)," "," "});
        }
    }
}

We know that i is the static variable ..This variable will store an integer (Value in the Row :- CurrentRow-1 and Column :- 0 of our JTable through the method mod.getValueAt(mod.getRowCount() - 1, 0) <---This method returns an Object hence we’ll need to parse it into an Integer )  which would get incremented whenever user presses the Enter Key …        if (evt.getKeyCode() == KeyEvent.VK_ENTER)    <--- This line is responsible to detect the enter key press … After variable I gets incremented we would add a new row to our JTable using this line --->  mod.addRow(new Object[]{String.valueOf(i)," "," "});









1 comment:

  1. With the many blogs which I have encountered, I never expected to see a very beautiful post online..After reading this one, I felt so lucky to see its content..-)

    ReplyDelete

Copyright © 2013 TechWayz.com

Search This Blog

Loading...