Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package GUI; import Extras.ButtonColumn; import Extras.JSON; import com.mycompany.crud_json_maven.Config; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONObject; /** * * @author Diegou */ public class MainJF extends javax.swing.JFrame { /** * Creates new form MainJF */ public MainJF() { initComponents(); initializeComponent(); } private void initializeComponent() { this.addWindowListener(new WindowAdapter() { public void windowActivated(WindowEvent e) { LlenarTabla(); } }); } public void LlenarTabla() { String[] columnNames = { "ID", "Nombre", "Email", "Edad", "Tipo", "", "" }; Object[][] data = null; DefaultTableModel model = new DefaultTableModel(data, columnNames); HttpResponse response; response = JSON.request(Config.URL + "usuarios/listar.json"); JSONObject jObject = JSON.JSON(response); try { JSONArray jsonArr = jObject.getJSONArray("data"); for (int i = 0; i < jsonArr.length(); i++) { JSONObject data_json = jsonArr.getJSONObject(i); model.addRow( new Object[] { data_json.get("idUsuario").toString(), data_json.get("nombre").toString(), data_json.get("email").toString(), data_json.get("edad").toString(), data_json.get("descripcion").toString(), "Editar", "Eliminar" }); } } catch (Exception e) { e.printStackTrace(); } tb_usuarios.setModel(model); Action editar = new AbstractAction() { public void actionPerformed(ActionEvent e) { JTable table = (JTable) e.getSource(); int modelRow = Integer.valueOf(e.getActionCommand()); String id = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 0); String nombre = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 1); String email = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 2); String edad = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 3); String tipo = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 4); FormUsuarios U = new FormUsuarios(); U.setID(id); U.setNombre(nombre); U.setEmail(email); U.setEdad(edad); U.setTipo(tipo); U.setLocationRelativeTo(null); U.setVisible(true); } }; ButtonColumn botonEditar = new ButtonColumn(tb_usuarios, editar, 5); botonEditar.setMnemonic(KeyEvent.VK_D); Action eliminar = new AbstractAction() { public void actionPerformed(ActionEvent e) { JTable table = (JTable) e.getSource(); int modelRow = Integer.valueOf(e.getActionCommand()); String id = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 0); String nombre = (String) ((DefaultTableModel) table.getModel()).getValueAt(modelRow, 1); int rs = JOptionPane.showConfirmDialog(null, "Estas seguro que deseas eliminas el usuario: " + nombre + " ?", "Eliminar", JOptionPane.YES_NO_OPTION); if (rs == JOptionPane.YES_OPTION) { List<NameValuePair> parametros = new ArrayList<NameValuePair>(); parametros.add(new BasicNameValuePair("idUsuario", id)); HttpResponse response = JSON.request(Config.URL + "usuarios/eliminar.json", parametros); JSONObject jObject = JSON.JSON(response); int code = Integer.parseInt(jObject.get("code").toString()); /*if(code == 201){ JOptionPane.showMessageDialog(null, "Usuario eliminado"); //((DefaultTableModel)table.getModel()).removeRow(modelRow); }else{ JOptionPane.showMessageDialog(null, "Error eliminar Usuario"); }*/ } } }; ButtonColumn botonEliminar = new ButtonColumn(tb_usuarios, eliminar, 6); botonEliminar.setMnemonic(KeyEvent.VK_D); model.fireTableDataChanged(); } public void refrescarTabla() { LlenarTabla(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); tb_usuarios = new javax.swing.JTable(); btn_add = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("API JSON"); tb_usuarios.setAutoCreateRowSorter(true); tb_usuarios .setModel(new javax.swing.table.DefaultTableModel(new Object[][] { {}, {}, {}, {} }, new String[] { })); jScrollPane1.setViewportView(tb_usuarios); btn_add.setText("Agregar Usuario"); btn_add.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_addActionPerformed(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().addContainerGap().addGroup(layout .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 928, Short.MAX_VALUE) .addGroup( layout.createSequentialGroup().addComponent(btn_add).addGap(0, 0, Short.MAX_VALUE))) .addContainerGap())); layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup( javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup().addContainerGap().addComponent(btn_add) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 356, Short.MAX_VALUE))); pack(); }// </editor-fold>//GEN-END:initComponents private void btn_addActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_addActionPerformed FormUsuarios U = new FormUsuarios(); U.setLocationRelativeTo(null); U.setVisible(true); }//GEN-LAST:event_btn_addActionPerformed /** * @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(MainJF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(MainJF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(MainJF.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(MainJF.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 MainJF().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_add; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tb_usuarios; // End of variables declaration//GEN-END:variables }