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:view.ResultsPanel.java

public void showHistogram(List<ElementaryMode> modes) {

    //for the JTable
    DefaultTableModel tableModel = new DefaultTableModel();
    JTable tableResult = new JTable();
    tableResult.setModel(tableModel);/*  www  .j a  v a  2  s  .  com*/

    tableModel.addColumn("Reaction");
    tableModel.addColumn("Presence in the modes");

    tableResult.setAutoCreateRowSorter(true);

    Map<Reaction, Double> stats = new HashMap<Reaction, Double>();

    DecimalFormat df = new DecimalFormat("0.00");

    for (ElementaryMode em : modes) {
        for (Reaction r : em.getContent().keySet()) {
            if (em.getContent().containsKey(r)) {
                if (!stats.containsKey(r)) {
                    stats.put(r, 1.0);
                } else {
                    Reaction key = r;
                    Double value = stats.get(r) + 1;
                    stats.remove(key);
                    stats.put(key, value);
                }
            }
        }
    }

    for (Reaction r : stats.keySet()) {
        tableModel
                .addRow(new Object[] { r, String.valueOf(df.format(stats.get(r) * 100 / modes.size())) + "%" });
    }

    JFrame statisticFrame = new JFrame();
    statisticFrame.add(new JScrollPane(tableResult), BorderLayout.CENTER);
    statisticFrame.setVisible(true);
    statisticFrame.setSize(400, 350);
    statisticFrame.setTitle("Representativeness of each reaction");
    statisticFrame.setLocation(500, 600);

    //histogram
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    Map<Integer, Integer> data = new TreeMap<Integer, Integer>();
    int maxSize = 0;
    for (ElementaryMode em : modes) {
        int modeLength = em.getContent().size();
        if (modeLength > maxSize) {
            maxSize = modeLength;
        }
        if (data.containsKey(modeLength)) {
            int value = data.get(modeLength) + 1;
            data.put(modeLength, value);
        } else {
            data.put(modeLength, 1);
        }
    }

    for (int i = 1; i < maxSize; i++) {
        if (!data.containsKey(i)) {
            data.put(i, 0);
        }
    }
    for (int key : data.keySet()) {
        dataset.addValue(Integer.valueOf((data.get(key))), "test", Integer.valueOf(key));
    }

    String plotTitle = "Number of reactions per elementary mode";
    String xaxis = "Reaction number";
    String yaxis = "Elementary mode number";
    PlotOrientation orientation = PlotOrientation.VERTICAL;
    boolean show = false;
    boolean toolTips = false;
    boolean urls = false;
    JFreeChart chart = ChartFactory.createBarChart3D(plotTitle, xaxis, yaxis, dataset, orientation, show,
            toolTips, urls);

    CategoryPlot plot = chart.getCategoryPlot();
    CategoryAxis axis = plot.getDomainAxis();

    plot.getDomainAxis(0).setLabelFont(plot.getDomainAxis().getLabelFont().deriveFont(new Float(11)));

    ChartFrame frame = new ChartFrame("Elementary modes", chart);
    frame.setVisible(true);
    frame.setSize(400, 350);
    frame.setLocation(500, 100);

}

From source file:userinterface.CyberSecurity.CyberSecurityJPanel.java

private void populateEmployeeTable(List<UserAccount> userAccounts) {
    DefaultTableModel model = (DefaultTableModel) employeeTable.getModel();
    employeeTable.removeAll();/*from   www . j  a  va 2  s.  co  m*/
    model.setRowCount(0);

    int serialNumber = 0;
    for (UserAccount userAccount : userAccounts) {
        LoginDetails latestLoginDetails = userAccount.getLatestLoginDetails();
        Employee employee = userAccount.getEmployee();
        List<Object> row = new ArrayList<>();
        row.add(++serialNumber);
        row.add(employee.getId());
        row.add(employee.getName());
        if (null != latestLoginDetails) {
            row.add(latestLoginDetails.getLoginDate() + " "
                    + LoginDetails.getFormattedTime(latestLoginDetails.getLoginTime()));
            row.add(latestLoginDetails.getLoginDate() + " "
                    + LoginDetails.getFormattedTime(latestLoginDetails.getLogoutTime()));
        } else {
            row.add("N/NA");
            row.add("N/A");
        }
        model.addRow(row.toArray());
    }
}

From source file:UserInterface.PoorPeopleRole.PoorPeopleWorkAreaJPanel.java

private void populateTransactionTable() {

    DefaultTableModel dtm = (DefaultTableModel) transactionJTable.getModel();
    dtm.setRowCount(0);/*from w w  w.j  ava  2s.  c  o  m*/

    for (Transaction objTransaction : objUserAccount.getObjPerson().getObjPoorPeopleTransactionDirectory()
            .getTransactionList()) {

        Object row[] = new Object[9];
        row[0] = objTransaction;
        row[1] = objTransaction.getTransactionSource();
        row[2] = (objTransaction.getObjUserAccountSource() == null) ? ("N/A")
                : (objTransaction.getObjUserAccountSource().getObjPerson());
        row[3] = objTransaction.getTransactionDestination();
        row[4] = (objTransaction.getObjUserAccountDestination() == null) ? ("N/A")
                : (objTransaction.getObjUserAccountDestination().getObjPerson());
        row[5] = objTransaction.getTransactionType();
        row[6] = objTransaction.getTransactionMode();
        row[7] = "$ " + String.valueOf(objTransaction.getTransactionBDAmount());
        row[8] = objTransaction.getTransactionDateToDisplay();

        dtm.addRow(row);
    }
}

From source file:la2launcher.MainFrame.java

private void processValidation(boolean full) {
    final long initTime = new Date().getTime();
    final String patcherUrl = "http://" + updateHost + "/hf/updater.lst.la2";//new ArrayBlockingQueue<Runnable>(10000)
    final ThreadPoolExecutor tpe = new ThreadPoolExecutor(5, 5, 1, TimeUnit.HOURS,
            new ArrayBlockingQueue<Runnable>(10000));
    tpe.execute(new Runnable() {
        @Override/*from  w  ww. j a  v  a2 s  .  c o m*/
        public void run() {
            jTextArea2.setText("");
            try {
                if (full) {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n?  ");
                } else {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n?  system");
                }
                File patcher = File.createTempFile("la2", "la2");
                patcher.deleteOnExit();
                File patcherExt = File.createTempFile("la2", "la2");
                patcherExt.deleteOnExit();
                FileOutputStream fos = new FileOutputStream(patcher);
                CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpGet httpGet = new HttpGet(patcherUrl);
                CloseableHttpResponse response1 = httpclient.execute(httpGet);

                HttpEntity entity1 = response1.getEntity();
                copyStream(entity1.getContent(), fos, null);
                response1.close();
                fos.close();
                jTextArea2.setText(jTextArea2.getText()
                        + "\r\n??  ? ?: " + patcherUrl);

                fixBzip2File(patcher);
                jTextArea2.setText(jTextArea2.getText() + "\r\n ?");

                BZip2CompressorInputStream bz = new BZip2CompressorInputStream(new FileInputStream(patcher));
                OutputStream pout = new FileOutputStream(patcherExt);
                copyStream(bz, pout, new CopyListener() {
                    @Override
                    public void transfered(int n) {
                        bytesRecieved += n;
                        bytesRecievedTotal += n;
                    }
                });
                pout.close();
                bz.close();
                jTextArea2.setText(jTextArea2.getText() + "\r\n? ?");

                if (full) {
                    jTextArea2.setText(jTextArea2.getText() + "\r\n  ");
                } else {
                    jTextArea2.setText(jTextArea2.getText()
                            + "\r\n     system");
                }

                DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
                model.setRowCount(0);

                int filesCount = scanSumFilesCount(patcherExt, full);
                jProgressBar1.setMinimum(0);
                jProgressBar1.setMaximum(filesCount);
                jProgressBar1.setValue(0);
                jLabel4.setText("0/" + filesCount);
                scanSumFile(patcherExt, new SumHandler() {

                    private ReentrantLock lock = new ReentrantLock();

                    @Override
                    public void handle(MDNamePair pair) {
                        try {
                            jProgressBar1.setIndeterminate(false);
                            //lock.unlock();
                            tpe.execute(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        lock.lock();
                                        //printMsg(pair.filename);
                                        String crc = digest(new File(gamePath + pair.filename));
                                        //printMsg("    : " + pair.crc);
                                        //printMsg("   ? ? : " + crc);
                                        if (!pair.crc.equals(crc)) {
                                            DefaultTableModel dtm = (DefaultTableModel) jTable2.getModel();
                                            dtm.addRow(new Object[] { pair.filename, false });
                                        }
                                        jProgressBar1.setValue(jProgressBar1.getValue() + 1);
                                        jLabel4.setText(jProgressBar1.getValue() + "/" + filesCount);
                                        lock.unlock();
                                    } catch (NoSuchAlgorithmException ex) {
                                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                                    } catch (IOException ex) {
                                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                                    } finally {
                                        //if (lock.isLocked()) lock.unlock();
                                    }
                                }
                            });
                        } finally {
                            //if (lock.isLocked()) lock.unlock();
                        }
                    }
                }, full);
            } catch (IOException ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    });

    jButton5.setEnabled(false);
    jButton6.setEnabled(false);
    jButton7.setEnabled(false);
    jButton8.setEnabled(false);
    jButton10.setEnabled(false);
    jProgressBar1.setIndeterminate(true);
    new Thread() {
        @Override
        public void run() {
            do {
                long millis = new Date().getTime();
                try {
                    sleep(300);
                } catch (InterruptedException ex) {
                    Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
                millis = new Date().getTime() - millis;
                BigDecimal totBig = new BigDecimal(bytesRecievedTotal / (1024 * 1024.0));
                totBig = totBig.setScale(2, BigDecimal.ROUND_CEILING);
                jLabel5.setText("?: " + (bytesRecieved / millis) + "KB/s. : "
                        + totBig + " MB");
                bytesRecieved = 0;
            } while (tpe.getActiveCount() > 0);
            tpe.shutdown();
            jButton5.setEnabled(true);
            jButton6.setEnabled(true);
            jButton7.setEnabled(true);
            jButton8.setEnabled(true);
            jButton10.setEnabled(true);
            jProgressBar1.setIndeterminate(false);
            printMsg("  " + (new Date().getTime() - initTime)
                    + " ?.");
        }
    }.start();
}

From source file:com.unsa.view.MainView.java

private void btnProcesarActionPerformed(java.awt.event.ActionEvent evt) throws SQLException, IOException {//GEN-FIRST:event_btnProcesarActionPerformed
    // TODO add your handling code here:
    if (lblInstitucion.getText().equals("") || lblInstitucion.getText().equals("")
            || lblIdioma.getText().equals("")) {

        JOptionPane.showMessageDialog(null, "Una de las opciones generales est vacio");
        return;//w w w .  j a  v a 2  s. co  m
    }
    if (jTextField1.getText().equals("")) {
        JOptionPane.showMessageDialog(null, "No se especific la ruta donde guardar la metadata");
        return;
    }

    jProgressBar1.setValue(0);
    jProgressBar1.setStringPainted(true);

    File[] listOfFiles = file.getSelectedFiles();
    int count = 0;

    for (File file : listOfFiles) {
        boolean archivo_daniado = false;
        if (file.isFile()) {
            System.out.println(file.getName());
            if (file.getName().substring(file.getName().length() - 1).equals("x")) { //is a docx
                try {

                    XWPFDocument doc = new XWPFDocument(new FileInputStream(file));

                    alg = new AlgorithmsWord(doc.getParagraphs());

                } catch (Exception e) {

                    archivo_daniado = true;
                }
            } else { //is not a docx
                try {

                    HWPFDocument doc = new HWPFDocument(new FileInputStream(file));

                    Range r = doc.getRange();
                    alg = new AlgorithmsWord(r);

                } catch (Exception e) {

                    try {
                        XWPFDocument doc = new XWPFDocument(new FileInputStream(file));
                        alg = new AlgorithmsWord(doc.getParagraphs());
                    } catch (Exception ex) {
                        archivo_daniado = true;
                    }
                }
            }

            Metadata metadata = null;
            if (archivo_daniado == true) {
                metadata = loadMetadataFail();
            } else {
                metadata = loadMetadata(alg);
            }
            metadata.setFileName(file.getName());
            listMetaData.add(metadata);
            int val_calculate = (count + 1) * 100 / listOfFiles.length;
            jProgressBar1.setValue(val_calculate);

            count++;

        }

    }

    String name = jTextField1.getText();

    ExcelController excel = new ExcelController(name, "UNSA", listMetaData);

    String[] lnames = { "Nombre Archivo", "Obs. Dudosa", "Obs. Critica", "Abrir Archivo" };
    DefaultTableModel model = new DefaultTableModel(lnames, 0);
    tableSalida.setModel(model);

    int contador = 0;
    for (Metadata meta : listMetaData) {
        Object[] data = new Object[4];
        data[0] = listOfFiles[contador].getName();

        if (meta.getFailGeneral()) {
            data[1] = "Fail";
            data[2] = "Fail";
        } else {
            data[1] = meta.getStadistic().getObservationGeneral() ? "Observacion" : "";
            data[2] = meta.getObservacionGeneral() ? "Falta" : "";
        }
        data[3] = "abrir";

        model.addRow(data);
        contador++;
    }

    btnAbrirMetadata.setEnabled(true);

}

From source file:gtu._work.etc.EnglishTester.java

void loadEnglishFile(File file) {
    englishFile = file;//from w w  w  .  j a v  a2 s.c  o m
    if (englishFile == null) {
        englishFile = new File(PropertiesUtil.getJarCurrentPath(EnglishTester.class), "english.properties");
    }
    try {
        englishProp = new Properties();
        englishProp.load(new FileInputStream(englishFile));
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (englishProp.isEmpty()) {
        englishProp.put("test1", "abc");
    }
    setTitle(englishFile.getName());
    DefaultTableModel propTableModel = JTableUtil.createModel(false, "english", "chinese");
    for (Enumeration<?> enu = englishProp.propertyNames(); enu.hasMoreElements();) {
        String key = (String) enu.nextElement();
        String value = englishProp.getProperty(key);
        propTableModel.addRow(new Object[] { key, value });
    }
    propTable.setModel(propTableModel);
}

From source file:userinterface.PatientRole.PatientLikeMeJPanel.java

public void populateRequestTable() {

    DefaultTableModel model = (DefaultTableModel) tblPatients.getModel();

    model.setRowCount(0);//from  w w  w . ja v  a 2s .com

    for (Network n : ecoSystem.getNetworkList()) {
        for (Enterprise ep : n.getEnterpriseDirectory().getEnterpriseList()) {
            if (ep instanceof HospitalEnterprise) {
                for (Organization o : ep.getOrganizationDirectory().getOrganizationList()) {
                    if (o instanceof PatientOrganization) {
                        for (Employee e : o.getEmployeeDirectory().getEmployeeList()) {
                            if (e instanceof Patient) {
                                if (((Patient) e).getPatientChronicDisease() != null) {
                                    if (((Patient) e).getPatientChronicDisease()
                                            .equalsIgnoreCase(patient.getPatientChronicDisease())) {
                                        if (e.getId() != patient.getId()) {
                                            Object[] row = new Object[3];
                                            row[0] = (Patient) e;
                                            row[1] = ((Patient) e).getCity();
                                            row[2] = ((Patient) e).getOccupation();
                                            model.addRow(row);
                                            //                               JOptionPane.showMessageDialog(null, "Hurray found!! " + e.getName());
                                        }
                                    }
                                }
                            }
                        }

                    }
                }
            }

        }
    }

    /* DefaultTableModel model = (DefaultTableModel)tblPatients.getModel();
             
     model.setRowCount(0);
             
     for(WorkRequest request : userAccount.getWorkQueue().getWorkRequestList()){
    if(request instanceof InspectionRequest){
        Object[] row = new Object[6];
        //row[0] = request;
        row[0] = ((InspectionRequest)request).getDrug();
        row[1] = request.getRequestDate();
        row[2] = ((InspectionRequest)request).getDrugManufacturerEnterprise();
        row[3] = ((InspectionRequest)request).getProblemExperienced();
        row[4] = request.getStatus();
        String result = ((InspectionRequest) request).getTestResult();
        row[5] = result == null ? "Waiting" : result;
                
        //row[4] = request.getStatus();
        model.addRow(row);
    }
     }*/
}

From source file:userinterface.Citizen.CitizenWorkAreaJPanel.java

public void populatePollutionLevelTable() {
    DefaultTableModel dtm = (DefaultTableModel) pollutionLevelTable.getModel();
    dtm.setRowCount(0);/*from   w  ww.  jav a 2  s. co  m*/
    ArrayList<Date> keyList = new ArrayList<>(
            account.getCitizen().getResidence().getPollutionMonitorSensor().getUsageHistory().keySet());
    Collections.sort(keyList);
    for (Date d : keyList) {
        PollutionMonitorSensorUsage usage = account.getCitizen().getResidence().getPollutionMonitorSensor()
                .getUsageHistory().get(d);
        if (null != usage && null != usage.getDate()) {
            Object row[] = new Object[2];
            row[0] = usage;
            if (usage.isPolluted()) {
                row[1] = "Polluted";
            } else {
                row[1] = "Clean";
            }
            dtm.addRow(row);
        }
    }

}

From source file:stockit.Manager.java

private void searchClientBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchClientBtnActionPerformed
    // TODO add your handling code here:
    if (listOfClients.isSelectionEmpty()) {
        JOptionPane.showMessageDialog(getContentPane(), "Please Select a Client", "Error",
                JOptionPane.ERROR_MESSAGE);
    } else {/*from   w ww.  j  a  v  a  2s.co m*/
        String selectedClient = listOfClients.getSelectedValue();
        System.out.println(selectedClient);
        try {
            DBConnection dbcon = new DBConnection();
            dbcon.establishConnection();
            Statement stmt = dbcon.con.createStatement();
            ResultSet rs = stmt.executeQuery(
                    "SELECT stock.stockID, company.Name, stock_sector.Sector, stock_daily_performance.Currency, stock_daily_performance.High, stock_daily_performance.Low, stock_daily_performance.Closing_Price, has_positions.Qty, (stock_daily_performance.Opening_Price - stock_daily_performance.Closing_Price) AS Today_Change, ((stock_daily_performance.Opening_Price - stock_daily_performance.Closing_Price) * has_positions.Qty) AS Profit\n"
                            + "FROM stock, stock_sector, stock_daily_performance, has_positions, account, client, company\n"
                            + "WHERE client.Name = '" + selectedClient + "'"
                            + "AND client.Client_SSN = account.Client_SSN AND account.Account_ID = has_positions.Account_ID AND stock_daily_performance.StockID = has_positions.Stock_ID AND stock.StockID = has_positions.Stock_ID AND stock_sector.StockID = has_positions.Stock_ID AND company.StockID = stock.StockID AND Date IN\n"
                            + "( Select * from \n" + "(\n" + "SELECT max(Date) \n"
                            + "FROM stock_daily_performance, stock\n"
                            + "where stock_daily_performance.StockID=stock.StockID\n"
                            + "group by stock.StockID\n" + "ORDER BY Date\n" + ") temp_table)");
            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.setRowCount(0);
            while (rs.next()) {
                System.out.println(
                        rs.getString("stockID") + "\t" + rs.getString("Name") + "\t" + rs.getString("Sector")
                                + "\t" + rs.getString("Currency") + "\t" + rs.getString("Closing_Price") + "\t"
                                + rs.getString("Qty") + rs.getString("Today_Change"));
                model.addRow(new Object[] { rs.getString("stockID"), rs.getString("Name"),
                        rs.getString("Sector"), rs.getString("Qty"), rs.getString("High"), rs.getString("Low"),
                        rs.getString("Closing_Price"), rs.getString("Today_Change"), rs.getString("Currency"),
                        rs.getString("Profit") });
            }
            dbcon.con.close();
        } catch (Exception ex) {
            Logger.getLogger(clientLogin.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:UserInterface.FinanceRole.DonateToPoorPeopleJPanel.java

private void populatePoorPeopleTable(CountryEnterprise objCountryEnterprise) {

    DefaultTableModel dtm = (DefaultTableModel) poorPeopleJTable.getModel();
    dtm.setRowCount(0);/*from ww  w.  j a v  a 2s .  co  m*/

    for (Organization objPPOrganization : objCountryEnterprise.getObjOrganizationDirectory()
            .getOrganizationList()) {
        if (objPPOrganization instanceof PoorPeopleOrganization) {
            for (UserAccount objUserAccount : objPPOrganization.getObjUserAccountDirectory()
                    .getUserAccountList()) {
                if (objUserAccount.getUserAccountStatus().equals(UserAccount.StatusType.Acitve.getValue())) {
                    Person objPerson = objUserAccount.getObjPerson();
                    if (objPerson.getPersonStatus().equals(Person.PersonRegStatusType.Active.getValue())) {

                        Object row[] = new Object[4];
                        row[0] = objPerson.getPersonInternationalID();
                        row[1] = objPerson;
                        row[2] = objUserAccount;
                        row[3] = objPerson.getObjFamilyMemberDirectory().getFamilyMemberList().size();

                        dtm.addRow(row);
                    }
                }
            }
        }
    }
}