Search in sources :

Example 1 with TableModel

use of javax.swing.table.TableModel in project groovy by apache.

the class TableSorter method compareRowsByColumn.

public int compareRowsByColumn(int row1, int row2, int column) {
    Class type = model.getColumnClass(column);
    TableModel data = model;
    // Check for nulls
    Object o1 = data.getValueAt(row1, column);
    Object o2 = data.getValueAt(row2, column);
    // If both values are null return 0
    if (o1 == null && o2 == null) {
        return 0;
    } else if (o1 == null) {
        // Define null less than everything.
        return -1;
    } else if (o2 == null) {
        return 1;
    }
    /* We copy all returned values from the getValue call in case
an optimised model is reusing one object to return many values.
The Number subclasses in the JDK are immutable and so will not be used in
this way but other subclasses of Number might want to do this to save
space and avoid unnecessary heap allocation.
*/
    if (type.getSuperclass() == java.lang.Number.class) {
        return compareNumbers(data, row1, column, row2);
    }
    if (type == java.util.Date.class) {
        return compareDates(data, row1, column, row2);
    }
    if (type == String.class) {
        return compareStrings(data, row1, column, row2);
    }
    if (type == Boolean.class) {
        return compareBooleans(data, row1, column, row2);
    }
    return compareObjects(data, row1, column, row2);
}
Also used : TableModel(javax.swing.table.TableModel)

Example 2 with TableModel

use of javax.swing.table.TableModel in project gephi by gephi.

the class ImportCSVUIVisualPanel1 method refreshPreviewTable.

public void refreshPreviewTable() {
    if (selectedFile != null && selectedFile.exists()) {
        try {
            CsvReader reader = new CsvReader(new FileInputStream(selectedFile), getSelectedSeparator(), getSelectedCharset());
            reader.setTrimWhitespace(false);
            String[] headers;
            try {
                reader.readHeaders();
                headers = reader.getHeaders();
            } catch (Exception ex) {
                //Some charsets can be problematic with unreal columns lenght. Don't show table when there are problems
                headers = new String[0];
            }
            columnCount = headers.length;
            //Check for repeated column names:
            Set<String> columnNamesSet = new HashSet<>();
            hasColumnNamesRepeated = false;
            hasSourceNodeColumn = false;
            hasTargetNodeColumn = false;
            int sourceColumnIndex = 0, targetColumnIndex = 0, currentColumn = 0;
            for (String header : headers) {
                if (header.equalsIgnoreCase("source")) {
                    hasSourceNodeColumn = true;
                    sourceColumnIndex = currentColumn;
                }
                if (header.equalsIgnoreCase("target")) {
                    hasTargetNodeColumn = true;
                    targetColumnIndex = currentColumn;
                }
                if (columnNamesSet.contains(header)) {
                    hasColumnNamesRepeated = true;
                    break;
                }
                columnNamesSet.add(header);
                currentColumn++;
            }
            ArrayList<String[]> records = new ArrayList<>();
            hasRowsMissingSourcesOrTargets = false;
            ImportCSVUIWizardAction.Mode mode = getMode();
            if (columnCount > 0) {
                String[] currentRecord;
                while (reader.readRecord()) {
                    int recordColumnCount = reader.getColumnCount();
                    currentRecord = new String[recordColumnCount];
                    for (int i = 0; i < currentRecord.length; i++) {
                        currentRecord[i] = reader.get(i);
                    }
                    // Search for missing source or target columns for edges table
                    if (mode == ImportCSVUIWizardAction.Mode.EDGES_TABLE) {
                        if (recordColumnCount < sourceColumnIndex || currentRecord[sourceColumnIndex].trim().isEmpty() || recordColumnCount < targetColumnIndex || currentRecord[targetColumnIndex].trim().isEmpty()) {
                            hasRowsMissingSourcesOrTargets = true;
                        }
                    }
                    if (records.size() < MAX_ROWS_PREVIEW) {
                        records.add(currentRecord);
                    }
                }
            }
            reader.close();
            final String[] columnNames = headers;
            final String[][] values = records.toArray(new String[0][]);
            previewTable.setModel(new TableModel() {

                @Override
                public int getRowCount() {
                    return values.length;
                }

                @Override
                public int getColumnCount() {
                    return columnNames.length;
                }

                @Override
                public String getColumnName(int columnIndex) {
                    return columnNames[columnIndex];
                }

                @Override
                public Class<?> getColumnClass(int columnIndex) {
                    return String.class;
                }

                @Override
                public boolean isCellEditable(int rowIndex, int columnIndex) {
                    return false;
                }

                @Override
                public Object getValueAt(int rowIndex, int columnIndex) {
                    if (values[rowIndex].length > columnIndex) {
                        return values[rowIndex][columnIndex];
                    } else {
                        return null;
                    }
                }

                @Override
                public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
                }

                @Override
                public void addTableModelListener(TableModelListener l) {
                }

                @Override
                public void removeTableModelListener(TableModelListener l) {
                }
            });
        } catch (FileNotFoundException ex) {
            Exceptions.printStackTrace(ex);
        } catch (IOException ex) {
            JOptionPane.showMessageDialog(this, getMessage("ImportCSVUIVisualPanel1.validation.error"), getMessage("ImportCSVUIVisualPanel1.validation.file-permissions-error"), JOptionPane.ERROR_MESSAGE);
        }
    }
    wizard1.fireChangeEvent();
    //To fire validation panel messages.
    pathTextField.setText(pathTextField.getText());
}
Also used : ArrayList(java.util.ArrayList) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) InvocationTargetException(java.lang.reflect.InvocationTargetException) CsvReader(com.csvreader.CsvReader) TableModelListener(javax.swing.event.TableModelListener) TableModel(javax.swing.table.TableModel) HashSet(java.util.HashSet)

Example 3 with TableModel

use of javax.swing.table.TableModel in project gephi by gephi.

the class JTableCSVExporter method writeCSVFile.

/**
     * <p>Export a JTable to the specified file.</p>
     * @param table Table to export
     * @param file File to write
     * @param separator Separator to use for separating values of a row in the CSV file. If null ',' will be used.
     * @param charset Charset encoding for the file
     * @param columnsToExport Indicates the indexes of the columns to export. All columns will be exported if null
     * @throws IOException When an error happens while writing the file
     */
public static void writeCSVFile(JTable table, File file, Character separator, Charset charset, Integer[] columnsToExport) throws IOException {
    TableModel model = table.getModel();
    FileOutputStream out = new FileOutputStream(file);
    if (separator == null) {
        separator = DEFAULT_SEPARATOR;
    }
    if (columnsToExport == null) {
        columnsToExport = new Integer[model.getColumnCount()];
        for (int i = 0; i < columnsToExport.length; i++) {
            columnsToExport[i] = i;
        }
    }
    CsvWriter writer = new CsvWriter(out, separator, charset);
    //Write column headers:
    for (int column = 0; column < columnsToExport.length; column++) {
        writer.write(model.getColumnName(columnsToExport[column]), true);
    }
    writer.endRecord();
    //Write rows:
    Object value;
    String text;
    for (int row = 0; row < table.getRowCount(); row++) {
        for (int column = 0; column < columnsToExport.length; column++) {
            value = model.getValueAt(table.convertRowIndexToModel(row), columnsToExport[column]);
            if (value != null) {
                text = value.toString();
            } else {
                text = "";
            }
            writer.write(text, true);
        }
        writer.endRecord();
    }
    writer.close();
}
Also used : CsvWriter(com.csvreader.CsvWriter) FileOutputStream(java.io.FileOutputStream) TableModel(javax.swing.table.TableModel)

Example 4 with TableModel

use of javax.swing.table.TableModel in project groovy-core by groovy.

the class TableSorter method compareRowsByColumn.

public int compareRowsByColumn(int row1, int row2, int column) {
    Class type = model.getColumnClass(column);
    TableModel data = model;
    // Check for nulls
    Object o1 = data.getValueAt(row1, column);
    Object o2 = data.getValueAt(row2, column);
    // If both values are null return 0
    if (o1 == null && o2 == null) {
        return 0;
    } else if (o1 == null) {
        // Define null less than everything.
        return -1;
    } else if (o2 == null) {
        return 1;
    }
    /* We copy all returned values from the getValue call in case
an optimised model is reusing one object to return many values.
The Number subclasses in the JDK are immutable and so will not be used in
this way but other subclasses of Number might want to do this to save
space and avoid unnecessary heap allocation.
*/
    if (type.getSuperclass() == java.lang.Number.class) {
        return compareNumbers(data, row1, column, row2);
    }
    if (type == java.util.Date.class) {
        return compareDates(data, row1, column, row2);
    }
    if (type == String.class) {
        return compareStrings(data, row1, column, row2);
    }
    if (type == Boolean.class) {
        return compareBooleans(data, row1, column, row2);
    }
    return compareObjects(data, row1, column, row2);
}
Also used : TableModel(javax.swing.table.TableModel)

Example 5 with TableModel

use of javax.swing.table.TableModel in project zaproxy by zaproxy.

the class ScanProgressDialog method getCopyToClipboardButton.

private JButton getCopyToClipboardButton() {
    if (copyToClipboardButton == null) {
        copyToClipboardButton = new JButton(Constant.messages.getString("ascan.progress.copyclipboard.button.label"));
        copyToClipboardButton.setToolTipText(Constant.messages.getString("ascan.progress.copyclipboard.button.tooltip"));
        copyToClipboardButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent evt) {
                // Mimics the implementation of BasicTableUI.TableTransferHandler.createTransferable(JComponent) but copies
                // all rows (including column names), not just selected rows/columns (which are none in this case).
                StringBuilder plainContent = new StringBuilder();
                StringBuilder htmlContent = new StringBuilder();
                htmlContent.append("<html>\n<body>\n<table>\n");
                TableModel tableModel = getMainPanel().getModel();
                htmlContent.append("<tr>\n");
                for (int col = 0; col < tableModel.getColumnCount(); col++) {
                    String val = tableModel.getColumnName(col);
                    plainContent.append(val).append('\t');
                    htmlContent.append("  <td>").append(val).append("</td>\n");
                }
                plainContent.deleteCharAt(plainContent.length() - 1).append("\n");
                htmlContent.append("</tr>\n");
                for (int row = 0; row < tableModel.getRowCount(); row++) {
                    htmlContent.append("<tr>\n");
                    for (int col = 0; col < tableModel.getColumnCount(); col++) {
                        Object obj = tableModel.getValueAt(row, col);
                        String val = (obj == null) ? "" : obj.toString();
                        plainContent.append(val).append('\t');
                        htmlContent.append("  <td>").append(val).append("</td>\n");
                    }
                    plainContent.deleteCharAt(plainContent.length() - 1).append("\n");
                    htmlContent.append("</tr>\n");
                }
                plainContent.deleteCharAt(plainContent.length() - 1);
                htmlContent.append("</table>\n</body>\n</html>");
                Transferable transferable = new BasicTransferable(plainContent.toString(), htmlContent.toString());
                try {
                    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(transferable, null);
                } catch (IllegalStateException e) {
                    View.getSingleton().showWarningDialog(ScanProgressDialog.this, Constant.messages.getString("ascan.progress.copyclipboard.error"));
                    log.warn("Failed to copy the contents to clipboard:", e);
                }
            }
        });
    }
    return copyToClipboardButton;
}
Also used : BasicTransferable(org.jdesktop.swingx.plaf.basic.core.BasicTransferable) ActionListener(java.awt.event.ActionListener) ActionEvent(java.awt.event.ActionEvent) JButton(javax.swing.JButton) Transferable(java.awt.datatransfer.Transferable) BasicTransferable(org.jdesktop.swingx.plaf.basic.core.BasicTransferable) TableModel(javax.swing.table.TableModel)

Aggregations

TableModel (javax.swing.table.TableModel)53 AbstractTableModel (javax.swing.table.AbstractTableModel)11 JTable (javax.swing.JTable)9 DefaultTableModel (javax.swing.table.DefaultTableModel)9 TableColumn (javax.swing.table.TableColumn)9 ArrayList (java.util.ArrayList)8 TableRowSorter (javax.swing.table.TableRowSorter)8 TableCellRenderer (javax.swing.table.TableCellRenderer)6 ActionEvent (java.awt.event.ActionEvent)5 JButton (javax.swing.JButton)5 JScrollPane (javax.swing.JScrollPane)5 TableCellEditor (javax.swing.table.TableCellEditor)5 Component (java.awt.Component)4 ActionListener (java.awt.event.ActionListener)4 List (java.util.List)4 Set (java.util.Set)4 TableColumnModel (javax.swing.table.TableColumnModel)4 IOException (java.io.IOException)3 HashSet (java.util.HashSet)3 AttributesTableModel (com.android.tools.idea.editors.theme.attributes.AttributesTableModel)2