JAVA - How To Add And Update A JTable Selected Row Using JOptionPane In Java
In this Java Tutorial we will see How To Add And Update A JTable Selected Row Using JOptionPane showInputDialog In Java Using NetBeans .
Project Source Code:
package java_tutorials;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
* @author 1bestcsharp.blogspot.com
*/
public class Java_JTable_Row_Add_Update_Using_JOptionPane extends javax.swing.JFrame {
/**
* Creates new form Java_JTable_Row_Add_Update_Using_JOptionPane
*/
public Java_JTable_Row_Add_Update_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();
BtnAddRow = new javax.swing.JButton();
BtnUpdateRow = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"1", "yhgbg", "azrt-tu", "10"},
{"2", "ryui", "bhjuil", "20"},
{"3", "hyjujhf", "wzerty", "30"},
{"4", "dgthyhrf", "iuygvc", "40"}
},
new String [] {
"Id", "First Name", "Last Name", "Age"
}
));
jScrollPane1.setViewportView(jTable1);
BtnAddRow.setText("Add Row");
BtnAddRow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnAddRowActionPerformed(evt);
}
});
BtnUpdateRow.setText("Update Row");
BtnUpdateRow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnUpdateRowActionPerformed(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()
.addGap(23, 23, 23)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(90, 90, 90)
.addComponent(BtnAddRow, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(BtnUpdateRow, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(36, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(BtnAddRow, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
.addComponent(BtnUpdateRow, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
// Button Add Row private void BtnAddRowActionPerformed(java.awt.event.ActionEvent evt) {
// get Data from showInputDialog
String id = JOptionPane.showInputDialog("Enter The Id");
String fn = JOptionPane.showInputDialog("Enter The First Name");
String ln = JOptionPane.showInputDialog("Enter The Last Name");
String age = JOptionPane.showInputDialog("Enter The Age");
// create a row with the given data
Object rowData[] = new Object[4];
rowData[0] = id;
rowData[1] = fn;
rowData[2] = ln;
rowData[3] = age;
// add row To the jtable
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(rowData);
}
// Button Update Selected Row private void BtnUpdateRowActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
// get the selected row index
int selectedRowIndex = jTable1.getSelectedRow();
try {
// get the data from the jtable model
String id = model.getValueAt(selectedRowIndex, 0).toString();
String fn = model.getValueAt(selectedRowIndex, 1).toString();
String ln = model.getValueAt(selectedRowIndex, 2).toString();
String age = model.getValueAt(selectedRowIndex, 3).toString();
// get the new data from showInputDialog
String newId = JOptionPane.showInputDialog(null,"The Id",id);
String newFN = JOptionPane.showInputDialog(null,"The First Name",fn);
String newLN = JOptionPane.showInputDialog(null,"The Last Name",ln);
String newAge = JOptionPane.showInputDialog(null,"The Age",age);
// insert the new data into the selected row
model.setValueAt(newId, selectedRowIndex, 0);
model.setValueAt(newFN, selectedRowIndex, 1);
model.setValueAt(newLN, selectedRowIndex, 2);
model.setValueAt(newAge, selectedRowIndex, 3);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"No Row Selected : "+e.getMessage());
}
}
/**
* @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_Row_Add_Update_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Java_JTable_Row_Add_Update_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Java_JTable_Row_Add_Update_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Java_JTable_Row_Add_Update_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_Row_Add_Update_Using_JOptionPane().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton BtnAddRow;
private javax.swing.JButton BtnUpdateRow;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
* @author 1bestcsharp.blogspot.com
*/
public class Java_JTable_Row_Add_Update_Using_JOptionPane extends javax.swing.JFrame {
/**
* Creates new form Java_JTable_Row_Add_Update_Using_JOptionPane
*/
public Java_JTable_Row_Add_Update_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();
BtnAddRow = new javax.swing.JButton();
BtnUpdateRow = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{"1", "yhgbg", "azrt-tu", "10"},
{"2", "ryui", "bhjuil", "20"},
{"3", "hyjujhf", "wzerty", "30"},
{"4", "dgthyhrf", "iuygvc", "40"}
},
new String [] {
"Id", "First Name", "Last Name", "Age"
}
));
jScrollPane1.setViewportView(jTable1);
BtnAddRow.setText("Add Row");
BtnAddRow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnAddRowActionPerformed(evt);
}
});
BtnUpdateRow.setText("Update Row");
BtnUpdateRow.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BtnUpdateRowActionPerformed(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()
.addGap(23, 23, 23)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 452, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(90, 90, 90)
.addComponent(BtnAddRow, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(32, 32, 32)
.addComponent(BtnUpdateRow, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(36, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(BtnAddRow, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
.addComponent(BtnUpdateRow, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(18, 18, 18)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
// Button Add Row private void BtnAddRowActionPerformed(java.awt.event.ActionEvent evt) {
// get Data from showInputDialog
String id = JOptionPane.showInputDialog("Enter The Id");
String fn = JOptionPane.showInputDialog("Enter The First Name");
String ln = JOptionPane.showInputDialog("Enter The Last Name");
String age = JOptionPane.showInputDialog("Enter The Age");
// create a row with the given data
Object rowData[] = new Object[4];
rowData[0] = id;
rowData[1] = fn;
rowData[2] = ln;
rowData[3] = age;
// add row To the jtable
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
model.addRow(rowData);
}
// Button Update Selected Row private void BtnUpdateRowActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
// get the selected row index
int selectedRowIndex = jTable1.getSelectedRow();
try {
// get the data from the jtable model
String id = model.getValueAt(selectedRowIndex, 0).toString();
String fn = model.getValueAt(selectedRowIndex, 1).toString();
String ln = model.getValueAt(selectedRowIndex, 2).toString();
String age = model.getValueAt(selectedRowIndex, 3).toString();
// get the new data from showInputDialog
String newId = JOptionPane.showInputDialog(null,"The Id",id);
String newFN = JOptionPane.showInputDialog(null,"The First Name",fn);
String newLN = JOptionPane.showInputDialog(null,"The Last Name",ln);
String newAge = JOptionPane.showInputDialog(null,"The Age",age);
// insert the new data into the selected row
model.setValueAt(newId, selectedRowIndex, 0);
model.setValueAt(newFN, selectedRowIndex, 1);
model.setValueAt(newLN, selectedRowIndex, 2);
model.setValueAt(newAge, selectedRowIndex, 3);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"No Row Selected : "+e.getMessage());
}
}
/**
* @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_Row_Add_Update_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Java_JTable_Row_Add_Update_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Java_JTable_Row_Add_Update_Using_JOptionPane.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Java_JTable_Row_Add_Update_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_Row_Add_Update_Using_JOptionPane().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton BtnAddRow;
private javax.swing.JButton BtnUpdateRow;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
// End of variables declaration
}
OutPut :
Download Projects Source Code