Home Answers Viewqa Swing-AWT How to delete and update from Jtable cell in swing app

 
 


vikas pandey
How to delete and update from Jtable cell in swing app
0 Answer(s)      9 months ago
Posted in : Swing AWT

Hii Sir, I am developing a swing app for adding,updating and deleting from jtable cells to database but i am getting following problems

  1. Whenever i click on delete button on selecting particular row which has to be deleted then last row is getting removed from the jtable but selected row is getting deleted from the database . I want to remove and delete the same row which is selected for the dletion.

  2. updation is happening for state column only and not happening for id,First name,Last name etc..

My Database column structure is :presid(int),firstname(varchar),last name(varchar),state(varchar),date(date).

plz sir help me to solve this problem.I am posting my code. Thanx in advance.

`

import java.awt.BorderLayout; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener;

import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent;

import java.sql.*; import java.text.ParseException;

import java.text.SimpleDateFormat;

import javax.swing.*; import javax.swing.table.DefaultTableModel;

public class Lesson38 extends JFrame {

static JLabel lFirstName, lLastName, lState, lBirthDate;
static JTextField tfFirstName, tfLastName, tfState, tfBirthDate;
static java.util.Date dateBirthDate, sqlBirthDate;
static ResultSet rows;
// Holds row values for the table
static Object[][] databaseResults;
// Holds column names for the table
static Object[] columns = {"ID", "First Name", "Last Name", "State", "Birth Date"};
// DefaultTableModel defines the methods JTable will use
// I'm overriding the getColumnClass
static DefaultTableModel dTableModel = new DefaultTableModel(databaseResults, columns) {

    public Class getColumnClass(int column) {
        Class returnValue;

        // Verifying that the column exists (index > 0 && index < number of columns

        if ((column >= 0) && (column < getColumnCount())) {
            returnValue = getValueAt(0, column).getClass();
        } else {

            // Returns the class for the item in the co6lumn  

            returnValue = Object.class;
        }
        return returnValue;
    }
};
// Create a JTable using the custom DefaultTableModel
static JTable table = new JTable(dTableModel);

public static void main(String[] args) {

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    // A connection object is used to provide access to a database

    Connection conn = null;

    try {
        // The driver allows you to query the database with Java
        // forName dynamically loads the class for you

        Class.forName("com.mysql.jdbc.Driver");

        // DriverManager is used to handle a set of JDBC drivers
        // getConnection establishes a connection to the database
        // You must also pass the userid and password for the database
        conn = DriverManager.getConnection("jdbc:mysql://localhost/techsoft", "root", "techsoft");

        // Statement objects executes a SQL query
        // createStatement returns a Statement object

        Statement sqlState = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_UPDATABLE);

        // This is the query I'm sending to the database

        String selectStuff = "Select pres_id, first_name, last_name, state, birth from president";

        // A ResultSet contains a table of data representing the
        // results of the query. It can not be changed and can
        // only be read in one direction

        rows = sqlState.executeQuery(selectStuff);

        // Temporarily holds the row results

        Object[] tempRow;

        // next is used to iterate through the results of a query

        while (rows.next()) {

            tempRow = new Object[]{rows.getInt(1), rows.getString(2), rows.getString(3), rows.getString(4), rows.getDate(5)};


            /*
             * You can also get other types 124 * int getInt() 125  * boolean
             * getBoolean() 126 * double getDouble() 127    * float getFloat()
             * 128  * long getLong() 129    * short getShort() 130
             */
            // Add the row of data to the JTable                     
            dTableModel.addRow(tempRow);
        }
    } catch (SQLException ex) {

        // String describing the error

        System.out.println("SQLException: " + ex.getMessage());

        // Vendor specific error code

        System.out.println("VendorError: " + ex.getErrorCode());
    } catch (ClassNotFoundException e) {
        // Executes if the driver can't be found
        e.printStackTrace();
    }

    // Increase the font size for the cells in the table

    table.setFont(new Font("Serif", Font.PLAIN, 15));

    // Increase the size of the cells to allow for bigger fonts

    table.setRowHeight(table.getRowHeight() + 12);
    // Allows the user to sort the data

    table.setAutoCreateRowSorter(true);

    // Adds the table to a scrollpane

    JScrollPane scrollPane = new JScrollPane(table);

    // Adds the scrollpane to the frame

    frame.add(scrollPane, BorderLayout.CENTER);

    // Creates a button that when pressed executes the code
    // in the method actionPerformed

    JButton addPres = new JButton("Add President");

    addPres.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            String sFirstName = "", sLastName = "", sState = "", sDate = "";
            // getText returns the value in the text field

            sFirstName = tfFirstName.getText();
            sLastName = tfLastName.getText();
            sState = tfState.getText();
            sDate = tfBirthDate.getText();

            sqlBirthDate = getADate(sDate);

            try {

                // Moves the database to the row where data will be placed                       
                rows.moveToInsertRow();

                // Update the values in the database

                rows.updateString("first_name", sFirstName);
                rows.updateString("last_name", sLastName);

                rows.updateString("state", sState);
                rows.updateDate("birth", (Date) sqlBirthDate);

                // Inserts the changes to the row values in the database

                rows.insertRow();

                // Directly updates the values in the database

                rows.updateRow();
            } catch (SQLException e1) {

                e1.printStackTrace();
            }

            int presID = 0;

            try {

                // Go to the last row inserted and get the id

                rows.last();
                presID = rows.getInt(1);
            } catch (SQLException e1) {

                e1.printStackTrace();
            }

            Object[] president = {presID, sFirstName, sLastName, sState, sqlBirthDate};
            // Add the row of values to the JTable

            dTableModel.addRow(president);

        }
    });

    JButton removePres = new JButton("Remove President");

    removePres.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            // Will remove which ever row that is selected

            dTableModel.removeRow(table.getSelectedRow()+1);
                System.out.println(table.getSelectedRow());
            try {
                // Moves the database to the row currently selected
                // getSelectedRow returns the row number for the selected row

                rows.absolute(table.getSelectedRow()+1);
                // Deletes the selected row from the database
                System.out.println(table.getSelectedRow());
                rows.deleteRow();

            } catch (SQLException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }
    });

    // Define values for my labels           
    lFirstName = new JLabel("First Name");
    lLastName = new JLabel("Last Name");
    lState = new JLabel("State");
    lBirthDate = new JLabel("Birthday");

    tfFirstName = new JTextField(15);
    tfLastName = new JTextField(15);
    tfState = new JTextField(15);
    // Set default text and size for text field

    tfBirthDate = new JTextField("yyyy-MM-dd", 10);

    // Create a panel to hold editing buttons and fields
    JPanel inputPanel = new JPanel();

    // Put components in the panel

    inputPanel.add(lFirstName);
    inputPanel.add(tfFirstName);
    inputPanel.add(lLastName);
    inputPanel.add(tfLastName);
    inputPanel.add(lState);
    inputPanel.add(tfState);
    inputPanel.add(lBirthDate);
    inputPanel.add(tfBirthDate);
    inputPanel.add(addPres);
    inputPanel.add(removePres);

    // Add the component panel to the frame

    frame.add(inputPanel, BorderLayout.SOUTH);

    // When the user clicks on a cell they'll be able to change the value

    table.addMouseListener(new MouseAdapter() {

        public void mouseReleased(MouseEvent me) {
            String value = JOptionPane.showInputDialog(null, "Enter Cell Value:");

            // Makes sure a value is changed only if OK is clicked

            if (value != null) {
                table.setValueAt(value, table.getSelectedRow(), table.getSelectedColumn());
            }


            try {
                // Move to the selected row

                rows.absolute(table.getSelectedRow() + 1);

                // Get the name of the selected column
                String updateCol = dTableModel.getColumnName(table.getSelectedColumn());
                System.out.println(updateCol);
                // Previous to Java 1.7 you couldn't use Strings in a Switch
                // If you get an error here it is because you aren't using Java 1.7

                switch (updateCol) {

                    // Uses a different update method depending on the data type

                    case "birth":
                        sqlBirthDate = getADate(value);
                        rows.updateDate(updateCol, (Date) sqlBirthDate);
                        rows.updateRow();
                        break;

                    default:
                        rows.updateString(updateCol, value);
                        System.out.println("Current Row: " + rows.getRow());
                         System.out.println(value);
                        rows.updateRow();
                        break;

                }


            } catch (SQLException e) {
                // Commented out so the user can delete rows
                // e.printStackTrace();                 }
            }
        }
    });


    frame.setSize(1200, 500);
    frame.setVisible(true);

}

// Will convert from string to date
public static java.util.Date getADate(String sDate) {

    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");

    try {
        dateBirthDate = dateFormatter.parse(sDate);
        sqlBirthDate = new java.sql.Date(dateBirthDate.getTime());
    } catch (ParseException e1) {

        e1.printStackTrace();
    }

    return sqlBirthDate;

}

} `

View Answers









Related Pages:
How to delete and update from Jtable cell in swing app
How to delete and update from Jtable cell in swing app  Hii Sir, I am developing a swing app for adding,updating and deleting from jtable... is getting removed from the jtable but selected row is getting deleted from
How to update,Delete database values from jtable cells ..
How to update,Delete database values from jtable cells ..  hello Sir... from database into jtable of a jpanel.. Now Sir, According to my need i have to update the cell values from there only means that whatever values i ma entering
How to update,Delete database values from jtable cells ..
How to update,Delete database values from jtable cells ..  Hello Sir... from database to jtable .Now as per my requirement i need to update and delete the database records from the table cells by entering new values there only
How to update,Delete database values from jtable cells ..
How to update,Delete database values from jtable cells ..  Hello Sir, I am working on a project in which i have to fetch the values from database to jtable .Now as per my requirement i need to update and delete the database
delete app from iphone
delete app from iphone  How to delete an existing app from itunes
how to make JTable to add delete and update sql database table
how to make JTable to add delete and update sql database table  Hello all I want to know how to make JTable to act actively to add delete and update database table. i am struck ed here from long time please help me
JTable - Cell selection - Swing AWT
JTable - Cell selection  How to select a cell of a JTable when I... javax.swing.event.*; public class JTableDemo extends JFrame { JTable table; DefaultTableModel tableModel; public JTableDemo() { table = new JTable(10, 5
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  ... ,update,delete database values from jtable only so i added three buttons add,update,delete .. mydatabase contains five columns id,name,address,contact,email
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  ... ,update,delete database values from jtable only so i added three buttons add,update...; JButton update; JButton insert; JButton delete; JPanel p; MyTableModel tm
How to insert and update all column values of database from jtable.
How to insert and update all column values of database from jtable.  ... ,update,delete database values from jtable only so i added three buttons add,update...; JButton update; JButton insert; JButton delete; JPanel p; MyTableModel tm
update a JTable - Java Beginners
update a JTable   how to update a JTable with Mysql data through user... in an updatable JTable You would create the table as follows: conn... = stat.executeQuery("SELECT * FROM register"); ResultSetTableModel model
JTable-Selecting a given cell - Swing AWT
JTable-Selecting a given cell  I tried the previous JTableDemo program but how to select a particular cell when i know the row,column number when button is clicked
JTable
JTable   how to select a definite cell which containing a similar text containg to the one which the user entering from a jtable at runtime in java
How to delete records from jtabel - Swing AWT
How to delete records from jtabel  hello I am using jtabel.... It is working properly.but now i want to delete rows from tabel at a time one row...; JFrame frame = new JFrame("Delete rows in the table!"); JPanel panel
JTable
JTable  Hi I have problems in setting values to a cell in Jtable... method tableChanged(TableModelEvent e) . I'll be loading values from data base when.... And i'm not able to set value to a particular column. How can i do it? Please
JTable Cell Validation? - Swing AWT
JTable Cell Validation?  hi there please i want a simple example of JTable with 3 columns Name,Number,Price and the first columns is string... or leave the cell empty nothing happens(the value still as it was) thank you all 
update a JTable - Java Beginners
update a JTable   i have tried your advice as how to update a JTable... main(String args[]) { JTable table; Connection con = null...); ResultSet rs = st.executeQuery("SELECT * FROM employee1
JTable - Swing AWT
JTable  Hi Deepak, i m facing a problem with jtable. i am able to display the values from the database into the jtable. but not able to modifying multiple cell values in a row. also i want to store those modified
java swing (jtable)
java swing (jtable)  hii..how to get values of a particular record in jtable from ms access database using java swing in netbeans..?? please help... from database and display it in jtable. import java.awt.*; import java.sql.
JTable
JTable  i want to delete record from JTable using a MenuItem DELETE. and values of JTable are fetched from database....please reply soon
Query on Java Swing - Table Cell Issue - Swing AWT
Query on Java Swing - Table Cell Issue  Hi, I have a query on Java... are using JTable which has 6 columns which are editable. When I use the TAB button from the key board focus is moving from one cell to another table cell but I am
how update JTable after adding a row into database
how update JTable after adding a row into database  J have two... in JTable, and it's OK, but after adding a row into database table does't update. How update JTable after adding a row into database? package djilepak.javaclss.for
How to create a JTable cell containing Image hyperlink?
How to create a JTable cell containing Image hyperlink?  I'm trying to find out how to create a JTable cell which contains Image, which should... in jTable cell is clicked, I want it to open a pop-up with some message showing
Update delete perticular row from brower on link - Struts
Update delete perticular row from brower on link   how can update and delete perticular row from List of employee in brower format are ramesh... page with textbox update , if delete click then that row also delete from
Setting Cell Values in JTable
Setting Cell Values in JTable       In this section, we will learn how to set the cell... about JTable. A cell is known as the format of  a row and a column in 
jtable
jtable  how to get the values from database into jtable and also add a checkbox into it and then when selected the checkbox it should again insert into database the selected chewckbox.plzz help
Getting Cell Values in a JTable
Getting Cell Values in a JTable       In this tutorial, you will learn how to get the cell values in a JTable component. It is a same as setting the cell values in a JTable
Java swing: Export excel sheet data to JTable
Java swing: Export excel sheet data to JTable In this tutorial, you will learn how to read data from excel file and export it to JTable. In swing applications, sometimes, it is required to display the excel file data into the jtable
swing
swing  How to fetch data from a row of a JTable and save the data in a database table dynamically? How to fetch data from database table and set the values in a Jtbale rows dynamically? How to set the no. of rows of a JTable
ABOUT Jtable
ABOUT Jtable  My Project is Exsice Management in java swing Desktop Application. I M Use Netbeans & Mysql . How can retrive Data in Jtable from Mysql Database in Net Beans
jtable insert row swing
jtable insert row swing  How to insert and refresh row in JTable?   Inserting Rows in a JTable example
DELETE
DELETE   I AM DOING IT IN MYSQL. DELETE FROM EMP WHERE SAL>(SELECT SAL FROM EMP WHERE ENAME='MILLAR') AND ENAME='ALLEN'; THIS IS GIVING...' for update in FROM clause ANY ONE PLEASE HELP ME. WITH REGARDS
Create a Custom Cell Renderer in a JTable
Create a Custom Cell Renderer in a JTable   ... cell renderer in a JTable component. Here, first of all you will know about the cell renderer in JTable. The cell renderer is the component of  JTable
JTable - Swing AWT
how could i show jtable data on the console. Thanks, Prashant   Hi...JTable  Hi Deepak, i want to display the Jtable data...*; public class JTableToConsole extends JFrame { public Object GetData(JTable
how to create a header in jtable using java swing
how to create a header in jtable using java swing  how to create a header in jtable using java swing   d
How To Display MS Access Table into Swing JTable - Java Beginners
How To Display MS Access Table into Swing JTable  How to Display Records From MS Access Database To JTable. Plz Help Me  Hi Friend... = DriverManager.getConnection("jdbc:odbc:access"); String sql = "Select * from
focustraversalpolicy taborder Swing JTable
focustraversalpolicy taborder Swing JTable  how to make a focustraversalpolicy that can make the tab order to jump over one column
delete
delete  how delete only one row in the database using jsp.database... = conn.createStatement(); st.executeUpdate("DELETE FROM employee WHERE empid...); String query = "select * from employee"; st = con.createStatement
Java JTable Question or Datagrid - Java Beginners
Java JTable Question or Datagrid  Hello Sir How I can Display data in to JTable or grid which is Stored in MS Access Databse with Add,Update... the following link: http://www.roseindia.net/java/example/java/swing/add_edit
How To Display both image and data into Swing JTable which is retrieved from ms access database
How To Display both image and data into Swing JTable which is retrieved from ms access database  So far this is my code how can i display both image and data from database.. while (rs.next()) { Vector row = new Vector(columns
Delete a row from database by id
. So anyone will tell me how to give hyper link to Delete and Update and delete...Delete a row from database by id  I m creating a small application...) for "DELETE" AND "UPDATE". On clicking delete which is hyper link that particular row
jtable problem
jtable problem  how to make a cell text hypertext
Enabling Row, Column and Cell Selections in a JTable
to describe how to enable the row, column and cell selections in a JTable... Enabling Row, Column and Cell Selections in a JTable... will see the enabling row, column and cell selections in a JTable. When you
How to use JTable with MS-Access
this data in JTable. How can I do it. I also want to EDIT and DELETE this Data.   Here is an example that retrieves the data from MS Access database...How to use JTable with MS-Access   I have Three Column in Database
How to use JTable with MS-Access
this data in JTable. How can I do it. I also want to EDIT and DELETE this Data.   Here is an example that retrieves the data from MS Access database...How to use JTable with MS-Access   I have Three Column in Database
Using insert update and delete in the same servlet
Using insert update and delete in the same servlet  How to write insert, update and delete coding in the same servlet
iPhone Make Call from App
iPhone Make Call from App  iPhone Make Call Programmatically I have created an application in iPhone that has the functionality to make Call from App. I am just wondering how to make a call programmatically... is there any
JTable populate with resultset.
JTable populate with resultset.  How to diplay data of resultset using JTable?   JTable is component of java swing toolkit. JTable class is helpful in displaying data in tabular format. You can also edit data. JTable
How to make a CRUD without using SQL Server? by just using your GUI? (CRUD = Creating, Register, Update, Delete)
How to make a CRUD without using SQL Server? by just using your GUI? (CRUD = Creating, Register, Update, Delete)  well I got a Program that can Register Update and delete a account to SQL Server. from now on we have to make
swing
swing  Write a java swing program to delete a selected record from a table

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.