Example usage for javax.swing.table DefaultTableModel setColumnCount

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

Introduction

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

Prototype

public void setColumnCount(int columnCount) 

Source Link

Document

Sets the number of columns in the model.

Usage

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   w w w. jav  a2  s  .  c om
        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: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;//  w w  w. j a  va 2 s  .  c  o 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:statisticsintegration.StatisticsLabr.java

private void ok2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ok2ActionPerformed
    Integer size = 0;//from   ww w  .  j av  a 2s.  c  om
    System.out.println("Nisulod");
    try {
        size = Integer.parseInt(Size.getText());
    } catch (Exception e) {
        Warnings.setText("Invalid size");
    }
    Warnings1.setText("");
    if (Categorical.isSelected() == true && Numerical.isSelected() == false) {
        String header[] = { "Values", "Percentage" };
        DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
        dtm.setRowCount(size);
        dtm.setColumnCount(2);

        for (int i = 0; i < jTable1.getColumnCount(); i++) {
            TableColumn column1 = jTable1.getTableHeader().getColumnModel().getColumn(i);
            column1.setHeaderValue(header[i]);
        }
    } //GEN-LAST:event_ok2ActionPerformed
    else if (Numerical.isSelected() == true && Categorical.isSelected() == false) {
        String header[] = { "VAL", "CL", "True CL", "MP", "FQ", "%", "CF", "C%" };
        DefaultTableModel dtm = (DefaultTableModel) jTable1.getModel();
        dtm.setRowCount(size);
        dtm.setColumnCount(8);

        for (int i = 0; i < jTable1.getColumnCount(); i++) {
            TableColumn column1 = jTable1.getTableHeader().getColumnModel().getColumn(i);
            column1.setHeaderValue(header[i]);
        }
    } else {
        Warnings1.setText("Select one operation");
    }
}

From source file:NewApplication.java

private void EditTable(Class clazz) {
    // TODO add your handling code here:

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

    model.setColumnCount(3);

    model.setNumRows(0);//from   ww w  . j a va  2 s  . c om

    jTable2.setModel(model);

    TableColumn tc = jTable2.getColumnModel().getColumn(0);
    tc.setHeaderValue("Field Name");
    tc = jTable2.getColumnModel().getColumn(1);
    tc.setHeaderValue("Value");
    tc = jTable2.getColumnModel().getColumn(2);
    tc.setHeaderValue("Type");

    try {

        Field[] fields = clazz.getDeclaredFields();

        for (Field f : fields) {

            Object[] obs = new Object[3];

            model = (DefaultTableModel) jTable2.getModel();

            f.setAccessible(true);

            obs[0] = f.getName();
            obs[2] = f.getType().getName();

            if (f.getName() == "" || f.getName() == null)
                continue;

            model.addRow(obs);

            jTable2.setModel(model);

        }

        jTable2.repaint();

    } catch (Exception ex) {
    }
    ;
}

From source file:NewApplication.java

private void EditTable(Class clazz, Object object) {
    // TODO add your handling code here:

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

    model.setColumnCount(3);

    model.setNumRows(0);/*from ww w.  j a v a2 s . c om*/

    jTable2.setModel(model);

    TableColumn tc = jTable2.getColumnModel().getColumn(0);
    tc.setHeaderValue("Field Name");
    tc = jTable2.getColumnModel().getColumn(1);
    tc.setHeaderValue("Value");
    tc = jTable2.getColumnModel().getColumn(2);
    tc.setHeaderValue("Type");

    try {

        Field[] fields = clazz.getDeclaredFields();

        for (Field f : fields) {

            Object[] obs = new Object[3];

            model = (DefaultTableModel) jTable2.getModel();

            f.setAccessible(true);

            obs[0] = f.getName();
            obs[1] = f.get(object);
            obs[2] = f.getType().getName();

            if (f.getName() == "" || f.getName() == null)
                continue;

            model.addRow(obs);

            jTable2.setModel(model);

        }

        jTable2.repaint();

    } catch (Exception ex) {
    }
    ;
}

From source file:NewApplication.java

private void EditTable() {
    // TODO add your handling code here:

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

    model.setColumnCount(3);

    model.setNumRows(0);/*from   ww w . j  a v  a2  s .c  o  m*/

    jTable2.setModel(model);

    TableColumn tc = jTable2.getColumnModel().getColumn(0);
    tc.setHeaderValue("Field Name");
    tc = jTable2.getColumnModel().getColumn(1);
    tc.setHeaderValue("Value");
    tc = jTable2.getColumnModel().getColumn(2);
    tc.setHeaderValue("Type");

    int index = listEntities.getSelectedIndex();

    if (index < 0)
        return;
    Class clazz = null;
    if (ens != null)
        clazz = (Class) ens.get(index);

    try {

        Field[] fields = clazz.getDeclaredFields();

        for (Field f : fields) {

            Object[] obs = new Object[3];

            model = (DefaultTableModel) jTable2.getModel();

            f.setAccessible(true);

            obs[0] = f.getName();
            obs[2] = f.getType().getName();

            if (f.getName() == "" || f.getName() == null)
                continue;

            model.addRow(obs);

            jTable2.setModel(model);

        }

        jTable2.repaint();

    } catch (Exception ex) {
    }
    ;
}

From source file:captureplugin.CapturePlugin.java

/**
 * Check the programs after data update.
 *///from www. j a  v  a 2 s .  com
public void handleTvDataUpdateFinished() {
    mNeedsUpdate = true;

    if (mAllowedToShowDialog) {
        mNeedsUpdate = false;

        DeviceIf[] devices = mConfig.getDeviceArray();

        final DefaultTableModel model = new DefaultTableModel() {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };

        model.setColumnCount(5);
        model.setColumnIdentifiers(new String[] { mLocalizer.msg("device", "Device"),
                Localizer.getLocalization(Localizer.I18N_CHANNEL), mLocalizer.msg("date", "Date"),
                ProgramFieldType.START_TIME_TYPE.getLocalizedName(),
                ProgramFieldType.TITLE_TYPE.getLocalizedName() });

        JTable table = new JTable(model);
        table.getTableHeader().setReorderingAllowed(false);
        table.getTableHeader().setResizingAllowed(false);
        table.getColumnModel().getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {
            public Component getTableCellRendererComponent(JTable renderTable, Object value, boolean isSelected,
                    boolean hasFocus, int row, int column) {
                Component c = super.getTableCellRendererComponent(renderTable, value, isSelected, hasFocus, row,
                        column);

                if (value instanceof DeviceIf) {
                    if (((DeviceIf) value).getDeleteRemovedProgramsAutomatically() && !isSelected) {
                        c.setForeground(Color.red);
                    }
                }

                return c;
            }
        });

        int[] columnWidth = new int[5];

        for (int i = 0; i < columnWidth.length; i++) {
            columnWidth[i] = UiUtilities.getStringWidth(table.getFont(), model.getColumnName(i)) + 10;
        }

        for (DeviceIf device : devices) {
            Program[] deleted = device.checkProgramsAfterDataUpdateAndGetDeleted();

            if (deleted != null && deleted.length > 0) {
                for (Program p : deleted) {
                    if (device.getDeleteRemovedProgramsAutomatically() && !p.isExpired() && !p.isOnAir()) {
                        device.remove(UiUtilities.getLastModalChildOf(getParentFrame()), p);
                    } else {
                        device.removeProgramWithoutExecution(p);
                    }

                    if (!p.isExpired()) {
                        Object[] o = new Object[] { device, p.getChannel().getName(), p.getDateString(),
                                p.getTimeString(), p.getTitle() };

                        for (int i = 0; i < columnWidth.length; i++) {
                            columnWidth[i] = Math.max(columnWidth[i],
                                    UiUtilities.getStringWidth(table.getFont(), o[i].toString()) + 10);
                        }

                        model.addRow(o);
                    }
                }
            }

            device.getProgramList();
        }

        if (model.getRowCount() > 0) {
            int sum = 0;

            for (int i = 0; i < columnWidth.length; i++) {
                table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth[i]);

                if (i < columnWidth.length - 1) {
                    table.getColumnModel().getColumn(i).setMaxWidth(columnWidth[i]);
                }

                sum += columnWidth[i];
            }

            JScrollPane scrollPane = new JScrollPane(table);
            scrollPane.setPreferredSize(new Dimension(450, 250));

            if (sum > 500) {
                table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
                scrollPane.getViewport().setPreferredSize(
                        new Dimension(sum, scrollPane.getViewport().getPreferredSize().height));
            }

            JButton export = new JButton(mLocalizer.msg("exportList", "Export list"));
            export.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    JFileChooser chooser = new JFileChooser();
                    chooser.setDialogType(JFileChooser.SAVE_DIALOG);
                    chooser.setFileFilter(new FileFilter() {
                        public boolean accept(File f) {
                            return f.isDirectory() || f.toString().toLowerCase().endsWith(".txt");
                        }

                        public String getDescription() {
                            return "*.txt";
                        }
                    });

                    chooser.setSelectedFile(new File("RemovedPrograms.txt"));
                    if (chooser.showSaveDialog(
                            UiUtilities.getLastModalChildOf(getParentFrame())) == JFileChooser.APPROVE_OPTION) {
                        if (chooser.getSelectedFile() != null) {
                            String file = chooser.getSelectedFile().getAbsolutePath();

                            if (!file.toLowerCase().endsWith(".txt") && file.indexOf('.') == -1) {
                                file = file + ".txt";
                            }

                            if (file.indexOf('.') != -1) {
                                try {
                                    RandomAccessFile write = new RandomAccessFile(file, "rw");
                                    write.setLength(0);

                                    String eolStyle = File.separator.equals("/") ? "\n" : "\r\n";

                                    for (int i = 0; i < model.getRowCount(); i++) {
                                        StringBuilder line = new StringBuilder();

                                        for (int j = 0; j < model.getColumnCount(); j++) {
                                            line.append(model.getValueAt(i, j)).append(' ');
                                        }

                                        line.append(eolStyle);

                                        write.writeBytes(line.toString());
                                    }

                                    write.close();
                                } catch (Exception ee) {
                                }
                            }
                        }
                    }
                }
            });

            Object[] message = {
                    mLocalizer.msg("deletedText",
                            "The data was changed and the following programs were deleted:"),
                    scrollPane, export };

            JOptionPane pane = new JOptionPane();
            pane.setMessage(message);
            pane.setMessageType(JOptionPane.PLAIN_MESSAGE);

            final JDialog d = pane.createDialog(UiUtilities.getLastModalChildOf(getParentFrame()),
                    mLocalizer.msg("CapturePlugin", "CapturePlugin") + " - "
                            + mLocalizer.msg("deletedTitle", "Deleted programs"));
            d.setResizable(true);
            d.setModal(false);

            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    d.setVisible(true);
                }
            });
        }
    }
}

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);// ww w  . j  a va2 s.c om

    //             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;
        }
    });

}

From source file:hw.java

private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
    //try {/*from  w w w. j  ava2  s . c om*/
    MongoCollection<Document> rcoll = db.getCollection("review");
    String business = jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString();

    BasicDBObject businessid = new BasicDBObject("business_id", business);

    FindIterable<Document> cursor2;

    jTextField8.setText("db.review.find(" + businessid.toString() + ")");
    cursor2 = rcoll.find(businessid);

    //             ResultSet rs = stmt.executeQuery(qry);
    String Columnames[] = { "user_id", "business_id", "text" };
    DefaultTableModel dtm = (DefaultTableModel) jTable2.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;
        }
    });

}

From source file:hw.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    MongoCollection<Document> coll = db.getCollection("user");
    String member_value = jTextField2.getText();
    String review_value = jTextField4.getText();
    String fans_value = jTextField5.getText();
    String average_stars_value = jTextField6.getText();
    String friends_value = jTextField7.getText();
    String review_dropdown = jComboBox13.getSelectedItem().toString();
    String fans_dropdown = jComboBox14.getSelectedItem().toString();
    String stars_dropdown = jComboBox15.getSelectedItem().toString();
    String friends_dropdown = jComboBox16.getSelectedItem().toString();
    BasicDBObject qryUser = new BasicDBObject();
    BasicDBList UserList = new BasicDBList();
    FindIterable<Document> cursor;
    String select = jComboBox1.getSelectedItem().toString();
    if (member_value == null && review_value.equals("0") && fans_value.equals("0")
            && average_stars_value.equals("0") && friends_value.equals("0")) {

        qryUser = null;/*from   w ww  . j a  v  a2 s .  co  m*/

    }
    if (member_value == null || member_value.equals("")) {
        member_value = "1999-01";
    }
    //      if(review_value == null || review_value.equals(""))
    //      {
    //          review_value = "0";
    //      }
    //      if(fans_value == null || fans_value.equals(""))
    //      {
    //          fans_value = "0";
    //      }
    //      if(average_stars_value == null || average_stars_value.equals(""))
    //      {
    //          average_stars_value = "0";
    //      }
    //      if(friends_value == null || friends_value.equals(""))
    //      {
    //          friends_value = "0";
    //      }

    if (!friends_value.equals("0")) {
        BasicDBObject fv = new BasicDBObject("friends." + friends_value, new BasicDBObject("$exists", true));
        UserList.add(fv);
    }
    if (!member_value.equals("0")) {
        BasicDBObject mv = new BasicDBObject("yelping_since", new BasicDBObject("$gt", member_value));
        UserList.add(mv);
    }
    if (!review_value.equals("0")) {
        if (review_dropdown.equals(">")) {
            BasicDBObject rv = new BasicDBObject("review_count",
                    new BasicDBObject("$gt", Integer.parseInt(review_value)));
            UserList.add(rv);
        }
        if (review_dropdown.equals("<")) {
            BasicDBObject rv = new BasicDBObject("review_count",
                    new BasicDBObject("$lt", Integer.parseInt(review_value)));
            UserList.add(rv);
        }
        if (review_dropdown.equals("=")) {
            BasicDBObject rv = new BasicDBObject("review_count", Integer.parseInt(review_value));
            UserList.add(rv);
        }

    }
    if (!fans_value.equals("0")) {
        if (fans_dropdown.equals(">")) {
            BasicDBObject f = new BasicDBObject("fans", new BasicDBObject("$gt", Integer.parseInt(fans_value)));
            UserList.add(f);
        }
        if (review_dropdown.equals("<")) {
            BasicDBObject f = new BasicDBObject("fans", new BasicDBObject("$lt", Integer.parseInt(fans_value)));
            UserList.add(f);
        }
        if (review_dropdown.equals("=")) {
            BasicDBObject f = new BasicDBObject("fans", Integer.parseInt(fans_value));
            UserList.add(f);
        }
    }
    if (!average_stars_value.equals("0")) {
        if (stars_dropdown.equals(">")) {
            BasicDBObject as = new BasicDBObject("average_stars",
                    new BasicDBObject("$gt", Integer.parseInt(average_stars_value)));
            UserList.add(as);
        }
        if (review_dropdown.equals("<")) {
            BasicDBObject as = new BasicDBObject("average_stars",
                    new BasicDBObject("$lt", Integer.parseInt(average_stars_value)));
            UserList.add(as);
        }
        if (review_dropdown.equals("=")) {
            BasicDBObject as = new BasicDBObject("average_stars", Integer.parseInt(average_stars_value));
            UserList.add(as);
        }
    }

    if ("AND".equals(jComboBox1.getSelectedItem().toString())) {
        qryUser = new BasicDBObject("$and", UserList);
    }
    if ("OR".equals(jComboBox1.getSelectedItem().toString())) {
        qryUser = new BasicDBObject("$or", UserList);
    }
    if (qryUser == null) {
        jTextField8.setText("db.user.find()");
        cursor = coll.find();

    } else {

        jTextField8.setText("db.user.find(" + qryUser.toString() + ")");
        cursor = coll.find(qryUser);
    }
    String Columnames[] = { "yelping_since", "review_count", "name", "user_id", "average_stars" };
    DefaultTableModel dtm = (DefaultTableModel) jTable2.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);

    }

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

            Object rowData[] = new Object[numberOfColumns];

            rowData[0] = document.get("yelping_since");
            rowData[1] = document.get("review_count");
            rowData[2] = document.get("name");
            rowData[3] = document.get("user_id");
            rowData[4] = document.get("average_stars");

            //                                System.out.print(document.get("yelping_since")+"\t");                                
            //                                System.out.print(document.get("review_count")+"\t");                                
            //                                System.out.print(document.get("name")+"\t");                                
            //                                System.out.print(document.get("user_id")+"\t");                                
            //                                System.out.print(document.get("average_stars")+"\t");                                
            //                                System.out.println();
            dtm.addRow(rowData);
            rowData = null;
        }
    });

    jTable2.setRowSelectionAllowed(true);
    jTable2.setModel(dtm);

    jTable2.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    dtm.fireTableDataChanged();

    // mongoClient.close();

    //        
    //        
    //      

}