Deleting rows with right click from MySql table in JTable Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Deleting rows with right click from MySql table in JTable without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have a Java class as shown below which displays my table from my database. I want to add a function that will open a pop-up menu and delete row from table. How can i do that?

    import java.awt.BorderLayout;
    import javax.swing.*;
    import java.sql.*;
    import java.util.Vector;

    public class Test {
        public static void main(String[] args) {
            Connection con = null;
            Statement st = null;
            ResultSet rs = null;
            String s;

            try {
                con = DriverManager.getConnection("jdbc:mysql://localhost/sms", "root", "");
                st = con.createStatement();
                s = "select * from sent_messages";
                rs = st.executeQuery(s);
                ResultSetMetaData rsmt = rs.getMetaData();
                int c = rsmt.getColumnCount();
                Vector column = new Vector(c);

                for (int i = 1; i <= c; i++) {
                    column.add(rsmt.getColumnName(i));
                }

                Vector data = new Vector();
                Vector row = new Vector();

                while (rs.next()) {
                    row = new Vector(c);

                    for (int i = 1; i <= c; i++) {
                        row.add(rs.getString(i));
                    }

                    data.add(row);
                }

                JFrame frame = new JFrame();
                frame.setSize(500, 600);
                frame.setLocationRelativeTo(null);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JPanel panel = new JPanel();
                JTable table = new JTable(data, column);
                JScrollPane jsp = new JScrollPane(table);
                panel.setLayout(new BorderLayout());
                    panel.add(jsp, BorderLayout.CENTER);            
                    frame.setContentPane(panel);
                    frame.setVisible(true);

                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "ERROR");
            } finally {
                try {
                    st.close();
                    rs.close();
                    con.close();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "ERROR CLOSE");
                }
            }
        }
    }

And as a reference i looked to this page but i couldn’t bind method from here.

Answer

I found an example and i took it as a reference.

I got to handle and rewrite the code as 3 classes shown below:

JTablePopupMenuExample.java

    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.beans.Statement;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.ResultSetMetaData;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Vector;

    import javax.swing.JFrame;
    import javax.swing.JMenuItem;
    import javax.swing.JPanel;
    import javax.swing.JPopupMenu;
    import javax.swing.JScrollPane;
    import javax.swing.JTable;
    import javax.swing.SwingUtilities;
    import javax.swing.table.DefaultTableModel;

    public class JTablePopupMenuExample extends JFrame implements ActionListener {


        private JTable table;
        private DefaultTableModel tableModel; 
        private JPopupMenu popupMenu;
        private JMenuItem menuItemAdd;
        private JMenuItem menuItemRemove;
        private JMenuItem menuItemRemoveAll;
        List<SentMessagesTable> msgList;

        public JTablePopupMenuExample() throws Exception{
            super("JTable Popup Menu Example");

            // sample table data
            String[] columnNames = new String[] {"id", "receiver", "sender", "msg_text", "status", "x_date"};



            msgList = new ArrayList<SentMessagesTable>();


            ResultSet rs = getTableRows();  


            while (rs.next()) {

                SentMessagesTable msg = new SentMessagesTable();

                msg.setId(rs.getInt("id"));
                msg.setReceiver(rs.getString("receiver"));
                msg.setSender(rs.getString("sender"));
                msg.setMsgText(rs.getString("msg_text"));
                msg.setStatus(rs.getString("status"));
                msg.setxDate(rs.getString("x_date"));

                msgList.add(msg);

            }

            String[][] rowDataTable = new String[34400][6];

            for(int i = 0 ; i < msgList.size();i++) {
                //burda jtable listesini doldur
                rowDataTable[i][0] = String.valueOf(msgList.get(i).getId());
                rowDataTable[i][1] = msgList.get(i).getReceiver();
                rowDataTable[i][2] = msgList.get(i).getSender();
                rowDataTable[i][3] = msgList.get(i).getMsgText();
                rowDataTable[i][4] = msgList.get(i).getStatus();
                rowDataTable[i][5] = msgList.get(i).getxDate(); 
            }

            // constructs the table with sample data
            tableModel = new DefaultTableModel(rowDataTable, columnNames);
            table = new JTable(tableModel);

            // constructs the popup menu
            popupMenu = new JPopupMenu();
            menuItemAdd = new JMenuItem("Add New Row");
            menuItemRemove = new JMenuItem("Remove Current Row");
            menuItemRemoveAll = new JMenuItem("Remove All Rows");

            menuItemAdd.addActionListener(this);
            menuItemRemove.addActionListener(this);
            menuItemRemoveAll.addActionListener(this);

            popupMenu.add(menuItemAdd);
            popupMenu.add(menuItemRemove);
            popupMenu.add(menuItemRemoveAll);

            // sets the popup menu for the table
            table.setComponentPopupMenu(popupMenu);

            table.addMouseListener(new TableMouseListener(table));

            // adds the table to the frame
            add(new JScrollPane(table));

            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(800,1000);
            setLocationRelativeTo(null);
        }

        public static void main(String[] args){             

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        new JTablePopupMenuExample().setVisible(true);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void actionPerformed(ActionEvent event) {
            JMenuItem menu = (JMenuItem) event.getSource();
            if (menu == menuItemAdd) {
                addNewRow();
            } else if (menu == menuItemRemove) {
                removeCurrentRow();
            } else if (menu == menuItemRemoveAll) {
                removeAllRows();
            }
        }

        private void addNewRow() {
            tableModel.addRow(new String[0]);
        }

        private void removeCurrentRow(){
            int selectedRow = table.getSelectedRow();
            tableModel.removeRow(selectedRow);



            String jdbcUrl = "jdbc:mysql://localhost/sms";
            String username = "root";
            String password = "";
            String sql = "delete from sent_messages where id = '"+msgList.get(selectedRow).getId()+"'";
           // java.sql.Statement stmt = null;

            try (Connection conn = DriverManager.getConnection(jdbcUrl, username, password); 
                java.sql.Statement stmt = conn.createStatement();) {

              stmt.executeUpdate(sql);
              System.out.println("Record deleted successfully");
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }   

        }

        private void removeAllRows() {
            int rowCount = tableModel.getRowCount();
            for (int i = 0; i < rowCount; i++) {
                tableModel.removeRow(0);
            }
        }


        private ResultSet getTableRows() throws SQLException {
            Connection con = null;
            java.sql.Statement st = null;
            ResultSet rs = null;
            String s;
            try {
                con = DriverManager.getConnection("jdbc:mysql://localhost/sms", "root", "");
                st = con.createStatement();
                s = "select * from sent_messages";
                rs = ((java.sql.Statement) st).executeQuery(s);


            }catch(Exception e) {
                    System.out.println(e.toString());
                }
             finally {
                //con.close();
            }

            return rs;
        }
    }

SentMessagesTable.java which involves (getters and setters)


public class SentMessagesTable {

    int id;
    String receiver;
    String sender;
    String msgText;
    String status;
    String xDate;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getReceiver() {
        return receiver;
    }

    public void setReceiver(String receiver) {
        this.receiver = receiver;
    }

    public String getSender() {
        return sender;
    }

    public void setSender(String sender) {
        this.sender = sender;
    }

    public String getMsgText() {
        return msgText;
    }

    public void setMsgText(String msgText) {
        this.msgText = msgText;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getxDate() {
        return xDate;
    }

    public void setxDate(String xDate) {
        this.xDate = xDate;
    }

}

And TableMouse Listener.java


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

import javax.swing.JTable;

public class TableMouseListener extends MouseAdapter {

    private JTable table;

    public TableMouseListener(JTable table) {
        this.table = table;
    }

    @Override
    public void mousePressed(MouseEvent event) {
        // selects the row at which point the mouse is clicked
        Point point = event.getPoint();
        int currentRow = table.rowAtPoint(point);
        table.setRowSelectionInterval(currentRow, currentRow);
    }
}

With that code i was able to delete records from JTable and also from my database.

We are here to answer your question about Deleting rows with right click from MySql table in JTable - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji