Example usage for javax.swing.table DefaultTableModel addColumn

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

Introduction

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

Prototype

public void addColumn(Object columnName) 

Source Link

Document

Adds a column to the model.

Usage

From source file:frames.MainGUI.java

public void LoadFeeDataToJTable(JTable t, File file) {
    try {//from   w w  w .  j  av a2s. c om
        CSVParser parser = CSVParser.parse(file, Charset.forName("UTF-8"), CSVFormat.DEFAULT);
        //t.setModel(tm);
        DefaultTableModel model = new DefaultTableModel();
        //model.setRowCount(0);
        for (CSVRecord c : parser) {
            if (c.getRecordNumber() == 1) {

                model.addColumn(c.get(datatype.GlobalVariable.TYPE));
                model.addColumn(c.get(datatype.GlobalVariable.AMOUNT));
                model.addColumn(c.get(datatype.GlobalVariable.PAID_BY));
                model.addColumn(c.get(datatype.GlobalVariable.PAYER));
                t.setModel(model);
                model = (DefaultTableModel) t.getModel();
                continue;
            }
            model.addRow(
                    new Object[] { c.get(datatype.GlobalVariable.TYPE), c.get(datatype.GlobalVariable.AMOUNT),
                            c.get(datatype.GlobalVariable.PAID_BY), c.get(datatype.GlobalVariable.PAYER) });
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:dylemator.UserList.java

private void filenameComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filenameComboActionPerformed
    Object item = this.filenameCombo.getSelectedItem();
    exportData = new ArrayList<String[]>();
    File file = new File(item.toString());
    if (file.exists()) {
        String datePattern = "(\\d+-\\d+-\\d+)";
        Pattern r = Pattern.compile(datePattern);
        Matcher m = r.matcher(file.getName());
        String fileDate;//from   www. j  a  v  a2 s .c o m
        if (m.find()) {
            fileDate = m.group(0);
        } else
            fileDate = new Date(file.lastModified()).toString();

        DefaultTableModel model = (DefaultTableModel) this.personsTable.getModel();
        model.setRowCount(0);
        model.setColumnCount(0);
        try {
            InputStreamReader input = new FileReader(file);
            BufferedReader bufferReader;
            bufferReader = new BufferedReader(input);
            // headers
            String headerLine = bufferReader.readLine();
            String[] headers = headerLine.split(";");
            // kod osoby i data badania
            String[] userHeaders = new String[] { headers[0], headers[1] };
            String[] valueHeaders = Arrays.copyOfRange(headers, 4, headers.length);
            Object[] allHeaders = ArrayUtils.addAll(userHeaders, valueHeaders);

            for (int header = 0; header < allHeaders.length; header++) {
                model.addColumn(allHeaders[header]);

            }
            exportData.add((String[]) allHeaders);

            String line;
            while ((line = bufferReader.readLine()) != null) {
                String[] fields = line.split(";");
                String[] userFields = new String[] { fields[0], fileDate };
                String[] valueFields = Arrays.copyOfRange(fields, 4, fields.length);
                Object[] allValues = ArrayUtils.addAll(userFields, valueFields);
                model.addRow(allValues);
                exportData.add((String[]) allValues);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FindDialog.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FindDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:localnetworkdrive.HomePage.java

private void Refbut1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Refbut1ActionPerformed
    // To fetch latest data on Videos from tracker and populate the gui containers

    //Fetch tracker ip
    trackerip = constants.Constants.serverIp + ":3000";
    uploadfile.setVisible(false);//from   w w  w. ja  v  a2 s .co m
    jScrollPane2.setVisible(true);
    filelist.setVisible(true);
    //Initialize tracker interface
    fetchfiles f = new fetchfiles();
    //Create image icons for display
    ImageIcon mp = new ImageIcon(HomePage.class.getResource("mp4.png"));
    //Carry out the fetch operation
    try {
        jsonresp = f.getHTML("http://" + trackerip + "/files/get/");
        if (jsonresp.equals("")) {
            JOptionPane.showMessageDialog(null, "Oops. Looks like the Server and I aren't connected.");
            return;
        }
        //Convert data into a convenient file format
        json = new JSONArray(jsonresp);
        //Create a data model for the table display
        DefaultTableModel model = new DefaultTableModel() {
            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            };
        };
        //Add initial columns
        model.addColumn("Icon");
        model.addColumn("FileName");
        model.addColumn("Remote Location");
        //Check if data isnt empty
        if (json.length() > 0)
            downloadbut1.setEnabled(true);
        //Iterate through the data fetched and populate the table display
        for (int i = 0; i < json.length(); i++) {
            String switcher = new pathtranslator().decode(json.getJSONObject(i).getString("absolutepath"));
            switch (switcher.split("[.]")[switcher.split("[.]").length - 1]) {
            case "mp4":
                model.addRow(new Object[] { mp, switcher, json.getJSONObject(i).getString("ip") });
                break;
            }
        }
        //Set the table display with updated data
        filelist1.setModel(model);
    } catch (HeadlessException | JSONException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
}

From source file:localnetworkdrive.HomePage.java

private void Refbut2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_Refbut2ActionPerformed
    // To fetch latest data on Screen Mirroring from tracker and populate the gui containers
    trackerip = constants.Constants.serverIp + ":3000";
    //Initialize tracker interface
    fetchfiles f = new fetchfiles();

    //Fetch latest data available for stream from tracker
    try {//from w  w  w .  ja  v a  2 s . co  m
        jsonresp = f.getHTML("http://" + trackerip + "/device/get");
        if (jsonresp.equals("")) {
            JOptionPane.showMessageDialog(null, "Oops. Looks like the Server and I aren't connected.");
            return;
        } else
            startstream.setEnabled(true);
        //Convert data into a convenient format
        json = new JSONArray(jsonresp);
        //Create a data model for the table display
        DefaultTableModel model = new DefaultTableModel() {
            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            };
        };
        //Populate initial columns on table display
        model.addColumn("IP Address");
        model.addColumn("Computer ID");
        //Check if data isnt empty
        if (json.length() > 0)
            downloadbut1.setEnabled(true);
        //Iterate through data to populate the table display
        for (int i = 0; i < json.length(); i++) {
            model.addRow(new Object[] { json.getJSONObject(i).getString("ip"),
                    json.getJSONObject(i).getString("hash") });
        }
        mirrorlist.setModel(model);
    } catch (HeadlessException | JSONException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }
}

From source file:localnetworkdrive.HomePage.java

private void RefbutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RefbutActionPerformed
    // To fetch latest data on Remote files from tracker and populate the gui containers

    //Fetch tracker ip
    trackerip = constants.Constants.serverIp + ":3000";
    uploadfile.setVisible(false);//from w  w w.ja va2 s.co  m
    jScrollPane2.setVisible(true);
    filelist.setVisible(true);
    //Initialize tracker interface
    fetchfiles f = new fetchfiles();
    //Create image icons for display
    ImageIcon jv = new ImageIcon(HomePage.class.getResource("java.png"));
    ImageIcon py = new ImageIcon(HomePage.class.getResource("python.png"));
    ImageIcon mp = new ImageIcon(HomePage.class.getResource("mp4.png"));
    ImageIcon def = new ImageIcon(HomePage.class.getResource("def.png"));
    ImageIcon pdf = new ImageIcon(HomePage.class.getResource("pdf.png"));
    //Carry out the fetch operation
    try {
        jsonresp = f.getHTML("http://" + trackerip + "/files/get/");
        if (jsonresp.equals("")) {
            JOptionPane.showMessageDialog(null, "Oops. Looks like the Server and I aren't connected.");
            return;
        }
        //Convert data into a convenient file format
        json = new JSONArray(jsonresp);
        //Create a data model for the table display
        DefaultTableModel model = new DefaultTableModel() {
            @Override
            public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
            };
        };
        //Add initial columns
        model.addColumn("Icon");
        model.addColumn("FileName");
        model.addColumn("Remote Location");
        //Check if data isnt empty
        if (json.length() > 0)
            downloadbut.setEnabled(true);
        //Iterate through the data fetched and populate the table display
        for (int i = 0; i < json.length(); i++) {
            String switcher = new pathtranslator().decode(json.getJSONObject(i).getString("absolutepath"));
            switch (switcher.split("[.]")[switcher.split("[.]").length - 1]) {
            case "py":
                model.addRow(new Object[] { py, switcher, json.getJSONObject(i).getString("ip") });
                break;
            case "java":
                model.addRow(new Object[] { jv, switcher, json.getJSONObject(i).getString("ip") });
                break;
            case "mp4":
                model.addRow(new Object[] { mp, switcher, json.getJSONObject(i).getString("ip") });
                break;
            case "pdf":
                model.addRow(new Object[] { pdf, switcher, json.getJSONObject(i).getString("ip") });
                break;
            default:
                model.addRow(new Object[] { def, switcher, json.getJSONObject(i).getString("ip") });
                break;
            }
        }
        //Set the table display with updated data
        filelist.setModel(model);
    } catch (HeadlessException | JSONException e) {
        JOptionPane.showMessageDialog(null, e.getMessage());
    }

}

From source file:dylemator.UserResultList.java

private void filenameComboActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_filenameComboActionPerformed
    Object item = this.filenameCombo.getSelectedItem();
    exportData = new ArrayList<String[]>();
    File file = new File(item.toString());
    if (file.exists()) {
        this.selectedFilename = item.toString();
        String datePattern = "(\\d+-\\d+-\\d+)";
        Pattern r = Pattern.compile(datePattern);
        Matcher m = r.matcher(file.getName());
        String fileDate;/*from w w w .  ja  v a  2s  .  co  m*/
        if (m.find()) {
            fileDate = m.group(0);
        } else
            fileDate = new Date(file.lastModified()).toString();

        DefaultTableModel codeModel = (DefaultTableModel) this.codeTable.getModel();
        DefaultTableModel infoModel = (DefaultTableModel) this.infoTable.getModel();
        DefaultTableModel resultsModel = (DefaultTableModel) this.resultsTable.getModel();
        codeModel.setRowCount(0);
        codeModel.setColumnCount(0);
        infoModel.setRowCount(0);
        infoModel.setColumnCount(2);
        resultsModel.setRowCount(0);
        resultsModel.setColumnCount(2);

        try {
            InputStreamReader input = new FileReader(file);
            BufferedReader bufferReader;
            bufferReader = new BufferedReader(input);
            // headers
            String headerLine = bufferReader.readLine();
            String[] headers = headerLine.split(";", -1);

            codeModel.addColumn(headers[0]);
            exportData.add((String[]) headers);

            String line;
            while ((line = bufferReader.readLine()) != null) {
                String[] fields = line.split(";", -1);
                exportData.add((String[]) fields);
                codeModel.addRow(new String[] { fields[0] });
            }

            bufferReader.close();
        } catch (FileNotFoundException ex) {
            Logger.getLogger(FindDialog.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(FindDialog.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:dataviewer.DataViewer.java

private void cb_tableActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cb_tableActionPerformed
    try {/*w w w. ja  v  a2  s .  c  o  m*/
        table = cb_table.getSelectedItem().toString();
        DB db = new DB("./db/" + table + ".db");
        db.open();
        String[] cols = db.get_table_columns(table);
        db.close();

        DefaultTableModel model = new DefaultTableModel();
        //model.addColumn("Column Index");
        model.addColumn("Field");
        int i = 1;

        StyleContext sc = StyleContext.getDefaultStyleContext();
        TabSet tabs = new TabSet(new TabStop[] { new TabStop(20) });
        AttributeSet paraSet = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.TabSet, tabs);
        tp_sql.setParagraphAttributes(paraSet, false);

        StyledDocument doc = tp_sql.getStyledDocument();

        doc.remove(0, doc.getLength());

        doc.insertString(doc.getLength(), "SELECT", null);
        doc.insertString(doc.getLength(), "\n", null);

        for (int j = 1; j < cols.length; ++j) {
            String s = cols[j];
            //model.addRow(new Object[]{i++, s});
            model.addRow(new Object[] { s });
            doc.insertString(doc.getLength(), "\t", null);
            doc.insertString(doc.getLength(), s, null);
            if (j < cols.length - 1) {
                doc.insertString(doc.getLength(), ",", null);
            }
            doc.insertString(doc.getLength(), "\n", null);
        }

        doc.insertString(doc.getLength(), "FROM", null);
        doc.insertString(doc.getLength(), "\n", null);
        doc.insertString(doc.getLength(), "\t", null);
        doc.insertString(doc.getLength(), table, null);
        /*doc.insertString(doc.getLength(), "\n", null);
         doc.insertString(doc.getLength(), "WHERE", null);
         doc.insertString(doc.getLength(), "\n", null);
         doc.insertString(doc.getLength(), "\t", null);
         doc.insertString(doc.getLength(), "_N_ <= " + N, null);
         doc.insertString(doc.getLength(), ";", null);*/

        tb_columns.setModel(model);

        TableRowSorter trs = new TableRowSorter(model);
        trs.setComparator(0, new IntComparator());
        tb_columns.setRowSorter(trs);

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

From source file:dataviewer.DataViewer.java

private void transpose(DefaultTableModel model) {
    try {//from w w w .j a v a2s . c o  m
        if (model.getColumnCount() == 0) {
            return;
        }
        DefaultTableModel new_model = new DefaultTableModel();

        // if not transposed
        if (!model.getColumnName(0).equals("_field_") && transpose == true) {
            new_model.addColumn("_field_");
            for (int r = 1; r <= model.getRowCount(); ++r) {
                new_model.addColumn("_col_" + r);
            }

            long n = 1;
            for (int c = 0; c < model.getColumnCount(); ++c) {
                Object[] s = new Object[new_model.getColumnCount()];
                String colname = model.getColumnName(c);
                int l = 0;
                s[l++] = colname;
                for (int r = 0; r < model.getRowCount(); ++r) {
                    s[r + l] = model.getValueAt(r, c);
                }
                new_model.addRow(s);
            }
        }
        if (model.getColumnName(0).equals("_field_") && transpose == false) {
            // if transposed
            for (int r = 0; r < model.getRowCount(); ++r) {
                new_model.addColumn(model.getValueAt(r, 0));
            }

            List<Integer> colIdx = new ArrayList();
            for (int c = 0; c < model.getColumnCount(); ++c) {
                if (!model.getColumnName(c).equals("_field_")) {
                    colIdx.add(c);
                }
            }

            for (int c = 0; c < colIdx.size(); ++c) {
                Object[] s = new Object[new_model.getColumnCount()];
                for (int r = 0; r < model.getRowCount(); ++r) {
                    s[r] = model.getValueAt(r, colIdx.get(c));
                }
                new_model.addRow(s);
            }
        }

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

From source file:dataviewer.DataViewer.java

private void view(String _sql) {

    final String sql = _sql;

    // check pivot

    t[THREAD.view.ordinal()].stop();//w w w .j av  a 2 s.  com
    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:hw.java

private void jTable2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable2MouseClicked

    MongoCollection<Document> rcoll = db.getCollection("review");
    String user = jTable2.getValueAt(jTable2.getSelectedRow(), 3).toString();

    BasicDBObject userid = new BasicDBObject("user_id", user);

    FindIterable<Document> cursor2;

    jTextField8.setText("db.review.find(" + userid.toString() + ")");
    cursor2 = rcoll.find(userid);/* w w  w  .ja  v  a2 s  .  co  m*/

    //             ResultSet rs = stmt.executeQuery(qry);
    String Columnames[] = { "user_id", "business_id", "text" };
    DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
    dtm.setColumnCount(0);
    dtm.setRowCount(0);
    int numberOfColumns = Columnames.length;

    for (int i = 0; i < numberOfColumns; i++) {
        String name = Columnames[i];
        dtm.addColumn(name);

    }

    cursor2.forEach(new Block<Document>() {
        @Override
        public void apply(final Document document) {

            Object rowData[] = new Object[numberOfColumns];

            rowData[0] = document.get("user_id");
            rowData[1] = document.get("business_id");
            rowData[2] = document.get("text");

            dtm.addRow(rowData);
            rowData = null;
        }
    });

}