user3868279
user3868279

Reputation: 7

How to delete a row from JTable while retaining it in the database

I am trying to delete a row from my JTable without sending updates to the bound MySQL database. To clarify: the deleted row should still be stored on the database but deleted from the JTable visible in my GUI.

import javax.swing.*;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
import javax.swing.table.DefaultTableModel;

import java.awt.*;
import java.awt.event.*;
import java.sql.*;

import com.mysql.*; 

import java.util.*;
public class Days {
private DefaultTableModel tblModel;
JTable days;
private JTextField ttask;
private JTextField ttime;
private JTextField txtSearch;
private Statement st;
private JButton add=new JButton("Add");
private JButton delete= new JButton("Delete");
private JPanel panelinfo;
private PreparedStatement ps;
JFrame frame;
Connection con;
ResultSet r;
public Days(final String s){
    frame = new JFrame();
    frame.setBounds(100, 100, 598, 470);
    frame.getContentPane().setLayout(null);
    frame.setTitle("NoTimeNoLife");
    panelinfo = new JPanel();
    panelinfo.setBorder(new TitledBorder(null, "Add your Schedule:", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panelinfo.setBounds(243, 76, 329, 135);

    JLabel a1 = new JLabel("Time :");
    a1.setBounds(10, 30, 46, 14);
    panelinfo.add(a1);
    JLabel a2 = new JLabel("Task :");
    a2.setBounds(10, 85, 46, 14);
    panelinfo.add(a2);
    frame.getContentPane().add(panelinfo);
    panelinfo.setLayout(null);


    add.setBounds(250, 222, 73, 30);
    frame.getContentPane().add(add);

    delete.setBounds(333, 222, 73, 30);
    frame.getContentPane().add(delete);

    ttime = new JTextField();
    ttime.setColumns(10);
    ttime.setBounds(93, 28, 206, 20);
    panelinfo.add(ttime);

    ttask = new JTextField();
    ttask.setColumns(10);
    ttask.setBounds(93, 84, 206, 20);
    panelinfo.add(ttask);

    JPanel panel = new JPanel();
    panel.setBorder(new TitledBorder(null, "DisplayId", TitledBorder.LEADING, TitledBorder.TOP, null, null));
    panel.setBounds(10, 76, 230, 86);
    frame.getContentPane().add(panel);
    panel.setLayout(null);

    txtSearch = new JTextField();
    txtSearch.setBounds(10, 26, 210, 20);
    panel.add(txtSearch);
    txtSearch.setColumns(10);

    String [] columnNames = {"id", "Time", "Task"};
    days = new JTable(new DefaultTableModel(null, new Object[]{"id", "Time","Task"}));
    tblModel = (DefaultTableModel) days.getModel();
    days = new JTable(tblModel){
          public boolean isCellEditable(int rowIndex, int colIndex) {
          return false; //Disallow the editing of any cell
          }
          };
            days.setBorder(new LineBorder(new Color(0, 0, 0)));
            days.setBounds(55, 314, 496, 116);
            JScrollPane scrollPane = new JScrollPane(days);
            scrollPane.setPreferredSize(new Dimension(452, 150));
            JPanel p1 = new JPanel();
            p1.setBounds(49, 263, 523, 159);
            p1.add(scrollPane);
            frame.getContentPane().add(p1);

BTW - can anybody explain to me the meaning of the following snippet: (Component[] com)? I copied this code so that table wouldn't be editable unless permission is given however I don't understand how it works as a whole.

    Component[] com = panelinfo.getComponents();  
            //Inside you action event where you want to disable everything  
            //Do the following  
            for (int a = 0; a < com.length; a++) {  
                 com[a].setEnabled(false);  
            }  

            frame.getContentPane().add(p1);
            try {
                con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testing1","root", "password");


            } catch (SQLException e) {
                System.out.println("Connection Failed! Check output console");
                e.printStackTrace();
            }
            displaydays(s); 
           add.addMouseListener(new MouseAdapter() {



                public void mouseClicked(MouseEvent arg0) {

                    if(add.getText().equalsIgnoreCase("Add")){              //equalsIgnoreCase ignores case sensitive

                    add.setText("Save");
                    delete.setText("Cancel");
                    days.setEnabled(false);
                    Component[] com = panelinfo.getComponents();  
                    //Inside you action event where you want to disable everything  
                    //Do the following  
                    for (int a = 0; a < com.length; a++) {  
                         com[a].setEnabled(true);  
                    }  
                    clear();
                    ttime.requestFocus();
                    }else{

                    int a = JOptionPane.showConfirmDialog(null, "Do you want to save this record?", "Message",  JOptionPane.YES_NO_OPTION);

                    if(a==0){

                        //try{
                            try {
                                st=con.createStatement();
                                if (arg0.getSource() == add){
                                    ps=con.prepareStatement("INSERT INTO "+s+" (Time, Task) values('" + ttime.getText() + "','" + ttask.getText() + "')");
                                }else{
                                ps=con.prepareStatement("UPDATE "+s+" set Time='" + ttime.getText() + "',Task ='" + ttask.getText() + "'where id ='" + ttime.getText() + "'" ); 

                                }
                                ps.executeUpdate();

                        defautview();
                        displaydays(s);


                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                    }


                    }


                }
                });

This is my "Delete" button which is supposed to delete data from the JTable but not from the database (currently my "Delete" button is deleting from the JTable AND the database).

 delete.addMouseListener(new MouseAdapter() {

                    public void mouseClicked(MouseEvent e) {
                        int a = JOptionPane.showConfirmDialog(null, "Do you want to delete this record?", "Message",  JOptionPane.YES_NO_OPTION);

                        if(a==0){

                        try {
                            st = con.createStatement();

                            ps = con.prepareStatement("delete from "+s+" where id ='" + txtSearch.getText() + "'");
                            System.out.println(ps);
                            ps.executeUpdate();
                            displaydays(s);
                            clear();

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

                    }
                });

         days.addMouseListener(new MouseAdapter() {

                public void mouseClicked(MouseEvent arg0) {
                    int selectedRowIndex = days.getSelectedRow();
                    //int selectedColumnIndex = tblList.getSelectedColumn();
                    String selectedObject = (String) days.getModel().getValueAt(selectedRowIndex, 0);

                txtSearch.setText(selectedObject);
                search(s);

                }
             });
}











    void defautview() {
        // TODO Auto-generated method stub
        add.setText("Add");
        delete.setText("Delete");
        days.setEnabled(true);
        Component[] com = panelinfo.getComponents();  
        //Inside you action event where you want to disable everything  
        //Do the following  
        for (int a = 0; a < com.length; a++) {  
             com[a].setEnabled(false);  
        }  
        clear();
    }
    void clear() {
        // TODO Auto-generated method stub
        ttime.setText("");
        ttask.setText("");// set time and task clear.
    }

     void displaydays(String s) {
            // TODO Auto-generated method stub
            try {
                 st = con.createStatement();

                r = st.executeQuery("select * from "+s);
                tblModel.getDataVector().removeAllElements();
                while(r.next()){

                    tblModel.addRow(new Object[]{r.getString("id"),r.getString("Time"),r.getString("Task")});// Display the Table into tblModel using ResultSet

                }

            } catch (SQLException e2) {
                // TODO Auto-generated catch block
                System.out.println("error");
                e2.printStackTrace();
            }
     }
    void search(String s){
        try {
            st = con.createStatement();

         ResultSet rs=st.executeQuery("SELECT * FROM "+s+" WHERE id='"+ txtSearch.getText() + "'");
         if(rs.next()){
             ttime.setText(rs.getString("Time").toString());
             ttask.setText(rs.getString("Task").toString());
         }

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

     }

     }

Upvotes: 0

Views: 1354

Answers (1)

joey rohan
joey rohan

Reputation: 3566

If you don't Want to delete it from database, don't call the dataBase code (on mouse click):

  st = con.createStatement();
  ps = con.prepareStatement("delete from "+s+" where id ='" + txtSearch.getText() + "'");
  System.out.println(ps);
  ps.executeUpdate();
  displaydays(s);

And add the code to delete the rows something like this :

DefaultTableModel dtm = new DefaultTableModel(rowName, colName);
table = new JTable(dtm);
dtm.removeRow(0); //remove first row

or

dtm.removeRow(index);

Upvotes: 1

Related Questions