Rabu, 29 April 2015

JAVA - How To Update A JTable Row Using JOptionPane showInputDialog In Java NetBeans

java jtable update row

JAVA - How To Update A JTable Row Using JOptionPane.showInputDialog In Java NetBeans

__________________________________________________________________________

In This Java Code We Will See How To Update JTable Row Using JOptionPane showInputDialog In Java Programming Language.


*Java Courses Java Complete Course
                            Java Swing Course



Project Source Code:


package java_tutorials;

import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 * @author 1bestcsharp.blogspot.com
 */
public class Java_JTable_Update_Row_Using_JOptionPane extends javax.swing.JFrame {

    /** Creates new form Java_JTable_Update_Row_Using_JOptionPane */
    public Java_JTable_Update_Row_Using_JOptionPane() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        Btn_UpdateRow = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"1", "gfdferghty", "aghgh", "900"},
                {"2", "hiuytrefd", "hjyuèhdsc", "00"},
                {"3", "uitefgh", "uiytebgh", "-100"},
                {"4", "fhjuyhgfd", "bfdrtyui", "33"},
                {"5", "uytre", "iuytrfbhnj", "50"}
            },
            new String [] {
                "Id", "First Name", "Last Name", "Age"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        Btn_UpdateRow.setText("Update Row");
        Btn_UpdateRow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                Btn_UpdateRowActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 447, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(172, 172, 172)
                        .addComponent(Btn_UpdateRow, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(15, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(37, Short.MAX_VALUE)
                .addComponent(Btn_UpdateRow, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26))
        );

        pack();
    }// </editor-fold>                        

// button update selected row
    private void Btn_UpdateRowActionPerformed(java.awt.event.ActionEvent evt) {                                              
        
        DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
        
// get selected row index
        int selectedRowIndex = jTable1.getSelectedRow();
        
// get selected row data 
        String id = model.getValueAt(selectedRowIndex, 0).toString();
        String fname = model.getValueAt(selectedRowIndex, 1).toString();
        String lname = model.getValueAt(selectedRowIndex, 2).toString();
        String age = model.getValueAt(selectedRowIndex, 3).toString();

 // get the entered data         
        String NewID = JOptionPane.showInputDialog(null,"Enter The New Id",id);
        String NewFN = JOptionPane.showInputDialog(null,"Enter The New First Name",fname);
        String NewLN = JOptionPane.showInputDialog(null,"Enter The New Last Name",lname);
        String NewAge = JOptionPane.showInputDialog(null,"Enter The New Age",age);
        
// set the new data into jtable row
        model.setValueAt(NewID, selectedRowIndex, 0);
        model.setValueAt(NewFN, selectedRowIndex, 1);
        model.setValueAt(NewLN, selectedRowIndex, 2);
        model.setValueAt(NewAge, selectedRowIndex,3);
    }                                             

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Java_JTable_Update_Row_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Java_JTable_Update_Row_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Java_JTable_Update_Row_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Java_JTable_Update_Row_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Java_JTable_Update_Row_Using_JOptionPane().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton Btn_UpdateRow;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration                   

}


////////OUTPUT:

jtable update row using joptionpane
jtable update row using joptionpane


Another Project Source Code:

package javaapp;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class Woirk extends JFrame {

    Object[] columns = {"ID","First Name","Last Name","Age"};
    Object[][] rows = {{1,"AA","BB",20},{2,"CC","DD",30},{3,"EE","FF",40},{4,"GG","HH",50}};
   
    public Woirk(){

        super("JFrame Name");
        
        JTable table = new JTable();
        
        JScrollPane pane = new JScrollPane();

        JButton button = new JButton("Upadate Row");
        
        JPanel panel = new JPanel(new BorderLayout());
        
        DefaultTableModel model = (DefaultTableModel)table.getModel();
        
        //set data to the model
        model.setDataVector(rows, columns);
        
        pane.setViewportView(table);

        panel.add(pane,BorderLayout.NORTH);
        
        panel.add(button,BorderLayout.SOUTH);
        
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
           
               String id;
               String fn;
               String ln;
               String age;
               
               //get values from yours showInputDialog
               id = JOptionPane.showInputDialog("Enter Your ID");
               fn = JOptionPane.showInputDialog("Enter Your First Name");
               ln = JOptionPane.showInputDialog("Enter Your Last Name");
               age = JOptionPane.showInputDialog("Enter Your Age");
               
               //get the selected row index
               int i = table.getSelectedRow();
               
               //set values to the specific place in jtable
               model.setValueAt(id, i, 0);
               model.setValueAt(fn, i, 1);
               model.setValueAt(ln, i, 2);
               model.setValueAt(age, i, 3);
            }
        });
        
        
        setContentPane(panel);
        setSize(800, 500);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true); 
    }
    
    public static void main(String[] args){

         new Woirk();
    }
}

////////OUTPUT:
update a row from jtable
before click on the button

update jtable row using joptionpane.showinputdialog
after click on the button ; enter the data in the input dialog

jtable row updated with data from showinputdialog
jtable row updated with data from showinputdialog



See: Add A Row To JTable Using JOptionPane showInputDialog

Bagikan

Jangan lewatkan

JAVA - How To Update A JTable Row Using JOptionPane showInputDialog In Java NetBeans
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.