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++) {

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

                while ( {
                    row = new Vector(c);

                    for (int i = 1; i <= c; i++) {


                JFrame frame = new JFrame();
                frame.setSize(500, 600);
                JPanel panel = new JPanel();
                JTable table = new JTable(data, column);
                JScrollPane jsp = new JScrollPane(table);
                panel.setLayout(new BorderLayout());
                    panel.add(jsp, BorderLayout.CENTER);            

                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "ERROR");
            } finally {
                try {
                } 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.


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

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

    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 ( {

                SentMessagesTable msg = new SentMessagesTable();




            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");



            // sets the popup menu for the table

            table.addMouseListener(new TableMouseListener(table));

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


        public static void main(String[] args){             

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

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

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

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

            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();) {

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


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

        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) {
             finally {

            return rs;
    } 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) { = 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

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;

    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