Example usage for javax.swing.table DefaultTableModel addRow

List of usage examples for javax.swing.table DefaultTableModel addRow

Introduction

In this page you can find the example usage for javax.swing.table DefaultTableModel addRow.

Prototype

public void addRow(Object[] rowData) 

Source Link

Document

Adds a row to the end of the model.

Usage

From source file:dataviewer.DataViewer.java

private void view(String _sql) {

    final String sql = _sql;

    // check pivot

    t[THREAD.view.ordinal()].stop();/*from w ww.j  ava  2 s.c  om*/
    t[THREAD.view.ordinal()] = new Thread(new Runnable() {
        @Override
        public void run() {

            try {
                Timing timer = new Timing();
                boolean alive = t[THREAD.read.ordinal()].isAlive();

                if (!alive) {
                    txt_count.setText("Running query ... ");
                }

                DB db = new DB("./db/" + table + ".db");
                db.open();

                ResultSet results = db.execute(sql);

                String csv = "";
                CSVWriter out = null;
                boolean asked = false;

                if (export && ck_export.isEnabled()) {
                    csv = JOptionPane.showInputDialog(new JFrame(""),
                            "Please enter the name of the file without extension.", "Export File Name",
                            JOptionPane.PLAIN_MESSAGE);
                    if (csv == null) {
                        csv = "";
                    }
                    if (!csv.equals("")) {
                        out = new CSVWriter(new FileWriter("./output/" + csv + ".txt"), '\n',
                                CSVWriter.NO_QUOTE_CHARACTER, CSVWriter.NO_ESCAPE_CHARACTER);
                    }
                }

                String _delimiter = StringEscapeUtils.unescapeJava(delimiter);
                StringBuilder sb = new StringBuilder();
                List<String> cols = new ArrayList();
                for (int i = 0; i < results.getMetaData().getColumnCount(); ++i) {
                    String name = results.getMetaData().getColumnName(i + 1);
                    cols.add(name);
                    sb.append(name).append(_delimiter);
                }
                sb.setLength(sb.length() - 1);

                DefaultTableModel model = new DefaultTableModel();
                for (int i = 0; i < cols.size(); ++i) {
                    model.addColumn(cols.get(i));
                }

                if (!csv.equals("")) {
                    out.writeNext(sb.toString());
                }

                String[] vals;
                long count = 0;
                boolean is_model_render = false;
                while (results.next()) {
                    count++;

                    vals = new String[cols.size()];

                    sb = new StringBuilder();
                    for (int i = 0; i < cols.size(); ++i) {
                        vals[i] = results.getString(cols.get(i));
                        sb.append(vals[i]).append(_delimiter);
                    }

                    sb.setLength(sb.length() - 1);
                    if (!csv.equals("")) {
                        out.writeNext(sb.toString());
                    }

                    if (asked == false && is_model_render == false && count > N) {
                        if (JOptionPane.showConfirmDialog(null, "Number of rows are more than " + N + ". Stop?",
                                "", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
                            renderData(model);
                            is_model_render = true;
                        }
                        asked = true;
                    }

                    if (is_model_render == false) {
                        model.addRow(vals);
                    }
                }

                db.close();
                if (is_model_render == false) {
                    if (transpose) {
                        tb_data.setModel(model);
                        transpose((DefaultTableModel) tb_data.getModel());
                    } else {
                        renderData(model);
                    }
                }

                if (!csv.equals("")) {
                    out.close();
                    txt_count.setText(count + " records are queried from " + table + " and exported to /output/"
                            + csv + ".txt. Took " + timer.getSec() + "s.");
                } else if (!alive) {
                    if (is_model_render) {
                        txt_count.setText(count + " records are queried from " + table + " but stopped at " + N
                                + ". Took " + timer.getSec() + "s.");
                    } else {
                        txt_count.setText(count + " records are queried from " + table + ". Took "
                                + timer.getSec() + "s.");
                    }
                }

            } catch (Exception e) {
                txt_count.setText(e.getMessage());
            }
        }
    });

    t[THREAD.view.ordinal()].start();
}

From source file:userInterface.SystemAdmin.PovertyAnalysisJPanel.java

/**
 * Creates new form PoveryAnalysisJPanel
 *//*from w ww.j a va  2 s .  c o  m*/
public PovertyAnalysisJPanel(JPanel userProcessContianer, EcoSystem business) {
    initComponents();
    this.ecoSystem = business;
    this.userProcessContainer = userProcessContianer;
    this.crimeDataset = new DefaultCategoryDataset();
    this.pireChartDataset = new DefaultPieDataset();

    int averageIncome = 0, num = 0, crminals = 0, crimeRate = 0, sumIncome = 0;
    int numBelowPoverty = 0;
    int doesHaveLicesnse = 0;
    int doesHaveLicesnsePercent = 0;
    DefaultTableModel model = (DefaultTableModel) povertyJTable.getModel();
    model.setRowCount(0);
    for (String networkKeys : business.getNetworkList().keySet()) {
        Network newNetwork = business.getNetworkList().get(networkKeys);
        crimeRate = 0;
        crminals = 0;
        num = 0;
        averageIncome = 0;
        sumIncome = 0;
        numBelowPoverty = 0;
        doesHaveLicesnse = 0;
        doesHaveLicesnsePercent = 0;
        personDirectory = newNetwork.getPersonDirectory();
        crimeRecords = newNetwork.getCrimeRecords();
        //JOptionPane.showMessageDialog(this, newNetwork);

        for (String personKeys : personDirectory.getPersonList().keySet()) {
            Person person = personDirectory.getPersonList().get(personKeys);
            if (person.getMonthlyIncome() > 0) {
                sumIncome = sumIncome + person.getMonthlyIncome();
                num++;
            }

        }
        averageIncome = sumIncome / num;
        //JOptionPane.showMessageDialog(povertyJTable, "Average Income for Netowrk "+ newNetwork.getName()+" is"+averageIncome);

        for (String personKeys : personDirectory.getPersonList().keySet()) {
            Person person = personDirectory.getPersonList().get(personKeys);
            if (person.getMonthlyIncome() > 0) {
                if (person.getMonthlyIncome() < averageIncome) {
                    //JOptionPane.showMessageDialog(povertyJTable, person.getFirstName() + " "+ person.getMonthlyIncome());
                    numBelowPoverty++;
                }
                if (person.getDoesHaveLicense() == 1) {
                    doesHaveLicesnse++;
                }

            }
            if (newNetwork.getCrimeRecords().searchPersonRecord(person.getSSN()) != null) {
                crminals++;
            }

        }
        //num++;
        //numBelowPoverty++;
        int poverty = (100 * numBelowPoverty) / num;
        crimeRate = (100 * crminals) / num;
        doesHaveLicesnsePercent = (100 * doesHaveLicesnse) / num;
        Object[] row = new Object[7];
        row[0] = newNetwork;
        row[1] = num;
        row[2] = averageIncome;
        row[3] = doesHaveLicesnsePercent;
        row[4] = poverty;
        row[5] = crimeRecords.getCrimeRecord().values().size();
        row[6] = crimeRate;
        model.addRow(row);

        crimeDataset.addValue(crimeRate, "Crime Rate", newNetwork.getName() + " Crime Rate");
        crimeDataset.addValue(poverty, "Poverty Rate", newNetwork.getName() + " Poverty Rate");
        crimeDataset.addValue(doesHaveLicesnsePercent, "People Having FireArms License",
                newNetwork.getName() + " FireArms Holders");
        pireChartDataset.setValue(newNetwork.getName(), crimeRecords.getCrimeRecord().values().size());
    }

}

From source file:com.declarativa.interprolog.gui.ListenerWindow.java

public void drawFragments() {
    java.util.List<String> args = new ArrayList<>();
    ArgBuildManager manag = new ArgBuildManager();
    args = manag.RetrieveArguments();/*w ww  . ja v a  2 s.  c o  m*/
    jTextArea1.append("List of built arguments:\n");
    for (Iterator<String> it = args.iterator(); it.hasNext();) {
        String string = it.next();
        jTextArea1.append("\t" + string + "\n");
    }

    DefaultTableModel defaultModel = (DefaultTableModel) jTable1.getModel();

    Object[][] rowData = { { "Hello", "World" } };
    Object[] columnNames = { "A", "B" };

    DefaultTableModel model = new DefaultTableModel(rowData, columnNames);
    //table = new JTable();
    jTable1.setModel(model);

    /*
     Vector newRow = new Vector();
     newRow.add("Total Amount Spend");
     newRow.add("G");
     newRow.add("SDFG");
     newRow.add("KASDPF");
     newRow.add("E9JASK");
     newRow.add("09DFJ SLD JI");
     */
    int sizearg = args.size();

    for (int j = 0; j < args.size(); j++) {
        Vector newRow = new Vector();

        newRow.add(" ");
        newRow.add(args.get(j));

        model.addRow(newRow);
    }

    //       model.addRow(newRow);
}

From source file:UserInterface.GarbageCollectorRole.GarbageCollectorWorkAreaJPanel.java

public void populateRequestTable() {
    DefaultTableModel model = (DefaultTableModel) jGarbageCollector.getModel();

    model.setRowCount(0);/*  www.  j  a v a 2 s .  c  om*/
    for (WorkRequest request : userAccount.getWorkQueue().getWorkRequestList()) {
        Object[] row = new Object[7];
        row[0] = request;
        String area = ((GarbageCollectorWorkRequest) request).getArea();
        row[1] = area;
        String metal = ((GarbageCollectorWorkRequest) request).getMetalGarbageStatus();
        row[2] = metal;
        row[3] = ((GarbageCollectorWorkRequest) request).getBiodegradableStatus();
        row[4] = ((GarbageCollectorWorkRequest) request).getPlasticStatus();
        row[5] = ((GarbageCollectorWorkRequest) request).getStatus();
        row[6] = ((GarbageCollectorWorkRequest) request).getSender();

        model.addRow(row);
    }
}

From source file:gui.Trabajadores.java

public void cargaSalario() {
    try {/*  www  .  j  a  va2s . c o m*/
        Database con = new Database();
        DefaultTableModel modelo = new DefaultTableModel();
        this.salario.setModel(modelo);
        Connection conn = con.conectar();
        String sentencia = "";
        PreparedStatement pst = conn.prepareStatement(sentencia);
        rs = pst.executeQuery();
        ResultSetMetaData rsMd = rs.getMetaData();
        //La cantidad de columnas que tiene la consulta
        int cantidadColumnas = rsMd.getColumnCount();
        //Establecer como cabezeras el nombre de las colimnas
        for (int i = 1; i <= cantidadColumnas; i++) {
            modelo.addColumn(rsMd.getColumnLabel(i));
        }
        //Creando las filas para el JTable
        while (rs.next()) {
            Object[] fila = new Object[cantidadColumnas];
            for (int i = 0; i < cantidadColumnas; i++) {
                fila[i] = rs.getObject(i + 1);
            }
            modelo.addRow(fila);
        }
        con.CerrarConexion();
    } catch (Exception ioe) {
        ioe.printStackTrace();
    }
}

From source file:GUI.MainWindow.java

private void deleteAffectedHosts() {

    System.out.println("==deleteAffectedHost");
    // Get reference to visible vulnerability
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) VulnTree.getLastSelectedPathComponent();
    Vulnerability vuln = (Vulnerability) node.getUserObject();

    // Build the list of hosts to delete
    int[] rows = this.VulnAffectedHostsTable.getSelectedRows();
    for (int i = 0; i < rows.length; i++) {
        int row = this.VulnAffectedHostsTable.convertRowIndexToModel(rows[i]);
        Object obj = this.VulnAffectedHostsTable.getModel().getValueAt(row, 0);
        if (obj instanceof Host) {
            Host host = (Host) obj;/*  w ww.j a  v  a2 s.c om*/
            System.out.println("To Delete: " + host + ":" + host.getPortnumber());
            vuln.deleteAffectedHost(host);
        }
    }

    // update the GUI
    DefaultTableModel dtm = (DefaultTableModel) this.VulnAffectedHostsTable.getModel();
    // Clear the existing table
    dtm.setRowCount(0);

    // Set affected hosts into table
    Enumeration enums = vuln.getAffectedHosts().elements();
    while (enums.hasMoreElements()) {
        Object obj2 = enums.nextElement();
        if (obj2 instanceof Host) {
            Host host2 = (Host) obj2;
            Vector vecrow = host2.getAsVector(); // Gets the first two columns from the host
            dtm.addRow(vecrow);
        }
    }
}

From source file:Interface.FoodCollectionSupervisor.FoodCollectionWorkArea.java

private void btnFindingDriversActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFindingDriversActionPerformed
    // TODO add your handling code here:
    int selectedRow = tblNewRequest.getSelectedRow();
    int nearestMiles = 0;
    if (selectedRow < 0) {
        JOptionPane.showMessageDialog(null, "Please select the row from the table.");
        return;/*from   ww w. j ava  2s  .co  m*/
    }

    btnAssignRequest.setEnabled(false);
    btnFindingDrivers.setName("Finding closest drivers...");

    btnFindingDrivers.setEnabled(false);

    jScrollPane6.setVisible(true);
    FoodCollectionWorkRequest request = (FoodCollectionWorkRequest) tblNewRequest.getValueAt(selectedRow, 0);
    String pickupAddress = request.getSender().getEmployee().getAddress();
    DefaultTableModel model = (DefaultTableModel) tblRecommendationDriver.getModel();
    model.setRowCount(0);
    for (UserAccount ua : organization.getUserAccountDirectory().getUserAccountList()) {
        Employee ee = ua.getEmployee();
        if (ee instanceof FoodCollectionDriverEmployee) {
            try {
                if (nearestMiles == 3) {
                    break;
                }

                String driverCurrentLocation = ((FoodCollectionDriverEmployee) (ee)).getDriverCurrentAddress();
                String sourceAddress = pickupAddress;
                String myKey = "AIzaSyDxQT-LVz0VhlZN_4FZ4NaKoa63zeGIge0";

                driverCurrentLocation = driverCurrentLocation.replace(" ", "+");
                sourceAddress = sourceAddress.replace(" ", "+");

                String url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=#ORIGIN&destinations=#DESTINATION&mode=driving&units=imperial&language=fr-FR&key=#KEY";
                url = url.replace("#ORIGIN", driverCurrentLocation);
                url = url.replace("#DESTINATION", sourceAddress);
                url = url.replace("#KEY", myKey);

                // HttpURLConnectionExample http = new HttpURLConnectionExample();

                // System.out.println("Testing 1 - Send Http GET request");
                String json = sendGet(url);

                String a = StringUtils.substringBefore(json, "miles");
                String b = StringUtils.substringAfterLast(a, "\"");
                b = b.replace(",", ".");
                String distance = b + "miles";
                //System.out.println("Distance : " + b +" miles.");

                Double bInMiles = Double.parseDouble(b);
                if (bInMiles < 2.0) {
                    nearestMiles++;
                }

                Object[] row = new Object[3];
                row[0] = ua.getEmployee().getName();
                row[1] = ((FoodCollectionDriverEmployee) (ee)).getDriverCurrentAddress();
                row[2] = distance;

                model.addRow(row);

            } catch (Exception e) {
                System.out.println("Message :" + e.getMessage());
            }
        }

    }

    btnAssignRequest.setEnabled(true);
    btnFindingDrivers.setName("Recommendation for closest driver >>");
    btnFindingDrivers.setEnabled(true);

}

From source file:GUI.MainWindow.java

private void showVulnerability(Vulnerability vulnerability) {

    // Unmap document listeners IF at all possible
    removeDocumentListeners();/*ww w . j  a v a 2 s  .  co m*/

    this.VulnTitleTextField.setText(vulnerability.getTitle());
    if (vulnerability.isIs_custom_risk() == true) {
        this.VulnCVSSVectorTextField.setText("NO CVSS VECTOR");
    } else {
        this.VulnCVSSVectorTextField.setText(vulnerability.getCvss_vector_string());
    }
    // Set vuln category
    this.VulnRiskCategory.setText(vulnerability.getRisk_category());
    this.VulnScore.setText("" + vulnerability.getRiskScore());
    this.VulnDescriptionTextPane.setText(vulnerability.getDescription());
    this.VulnRecommendationTextPane.setText(vulnerability.getRecommendation());

    // clear old references
    DefaultListModel ref_model = (DefaultListModel) this.VulnReferencesList.getModel();
    ref_model.removeAllElements();
    // add in the new references
    Enumeration ref_enums = vulnerability.getReferences().elements();
    while (ref_enums.hasMoreElements()) {
        Reference ref = (Reference) ref_enums.nextElement();
        ref_model.addElement(ref);
    }

    // Now setup undo listeners
    setupUndoListeners();
    setupDocumentListeners();

    DefaultTableModel dtm = (DefaultTableModel) this.VulnAffectedHostsTable.getModel();
    // Clear the existing table
    dtm.setRowCount(0);

    // Set affected hosts into table
    Enumeration enums = vulnerability.getAffectedHosts().elements();
    while (enums.hasMoreElements()) {
        Object obj = enums.nextElement();
        if (obj instanceof Host) {
            Host host = (Host) obj;
            Vector row = host.getAsVector(); // Gets the first two columns from the host
            dtm.addRow(row);
        }
    }

}

From source file:gui.Trabajadores.java

public void cargaNoSin() {
    try {/* w w  w .  j a va 2  s  .c o  m*/
        Database con = new Database();
        DefaultTableModel modelo = new DefaultTableModel();
        this.tablaNoSin.setModel(modelo);
        Connection conn = con.conectar();
        String sentencia = "SELECT d_sexo, count(d_sexo) from icave.fact_empleado where q_activo= 'SI' GROUP By d_sexo;";
        PreparedStatement pst = conn.prepareStatement(sentencia);
        rs = pst.executeQuery();
        ResultSetMetaData rsMd = rs.getMetaData();
        //La cantidad de columnas que tiene la consulta
        int cantidadColumnas = rsMd.getColumnCount();
        //Establecer como cabezeras el nombre de las colimnas
        for (int i = 1; i <= cantidadColumnas; i++) {
            modelo.addColumn(rsMd.getColumnLabel(i));
        }
        //Creando las filas para el JTable
        while (rs.next()) {
            Object[] fila = new Object[cantidadColumnas];
            for (int i = 0; i < cantidadColumnas; i++) {
                fila[i] = rs.getObject(i + 1);
            }
            modelo.addRow(fila);
        }
        con.CerrarConexion();
    } catch (Exception ioe) {
        ioe.printStackTrace();
    }
}

From source file:gui.Trabajadores.java

public void cargaEdad() {
    try {//from ww w  .jav a2s  .  c o  m
        Database con = new Database();
        DefaultTableModel modelo = new DefaultTableModel();
        this.edad.setModel(modelo);
        Connection conn = con.conectar();
        String sentencia = "select Num_Empleado,Fecha_Baja,Costo_Finiquito, Indemnizacion, Prima_Antiguedad, Gratificacion, Total_Pagado_Separacion, Motivo_Baja, Volver_Contratar, Pendiente from bajas_temp;";
        PreparedStatement pst = conn.prepareStatement(sentencia);
        rs = pst.executeQuery();
        ResultSetMetaData rsMd = rs.getMetaData();
        //La cantidad de columnas que tiene la consulta
        int cantidadColumnas = rsMd.getColumnCount();
        //Establecer como cabezeras el nombre de las colimnas
        for (int i = 1; i <= cantidadColumnas; i++) {
            modelo.addColumn(rsMd.getColumnLabel(i));
        }
        //Creando las filas para el JTable
        while (rs.next()) {
            Object[] fila = new Object[cantidadColumnas];
            for (int i = 0; i < cantidadColumnas; i++) {
                fila[i] = rs.getObject(i + 1);
            }
            modelo.addRow(fila);
        }
        con.CerrarConexion();
    } catch (Exception ioe) {
        ioe.printStackTrace();
    }
}