Java - Move JTable Row Up And Down

How To Move JTable Selected Rows Up N Down In Java Using NetBeans

move jtable selected row up and down in java



In this Java Tutorial we will see How To Get Jtable Selected Row And Move This Row Up & Down By Changing The position Using DefaultTableModel, moveRow() Function On  Two Buttons Click Event  In  Java Programming language And NetBeans IDE .




Project Source Code:

    // change jtable selection background color
    jTable1.setSelectionBackground(Color.BLACK);


   
    boolean row_Is_Selected = false;
    int index;
    DefaultTableModel model;


    // move selected row up
    private void jButtonUPActionPerformed(java.awt.event.ActionEvent evt) {                               
        if(row_Is_Selected == false)
        {
            model = (DefaultTableModel)jTable1.getModel();
            row_Is_Selected = true;
        }
        
        index = jTable1.getSelectedRow();
        if(index > 0){
            // move rows from the index to index into the position index -1
            model.moveRow(index, index, index - 1);
            // set selection to the new position
            jTable1.setRowSelectionInterval(index - 1, index - 1);
            
        }
    }                                         


    // move selected row down
    private void jButtonDownActionPerformed(java.awt.event.ActionEvent evt) {                           
        if(row_Is_Selected == false)
        {
            model = (DefaultTableModel)jTable1.getModel();
            row_Is_Selected = true;
        }
        
        index = jTable1.getSelectedRow();
        if(index < model.getRowCount() - 1){
            model.moveRow(index, index, index + 1);
            jTable1.setRowSelectionInterval(index + 1, index + 1);
            
        }
    }                                           



////// OUTPUT : 

move jtable selected row up and down



Share this

Related Posts

Previous
Next Post »