Example usage for javax.swing.table TableModel getValueAt

List of usage examples for javax.swing.table TableModel getValueAt

Introduction

In this page you can find the example usage for javax.swing.table TableModel getValueAt.

Prototype

public Object getValueAt(int rowIndex, int columnIndex);

Source Link

Document

Returns the value for the cell at columnIndex and rowIndex.

Usage

From source file:org.formic.wizard.step.gui.RequirementsValidationStep.java

/**
 * {@inheritDoc}//from   w  ww.j  a v  a 2  s  .co m
 * @see org.formic.wizard.WizardStep#displayed()
 */
public void displayed() {
    form.showInfoMessage(null);
    requirementInfo.setText(null);
    retryButton.setEnabled(false);

    setBusy(true);
    try {
        Integer result = (Integer) Worker.post(new Task() {
            public Object run() throws Exception {
                Integer result = OK;
                TableModel model = table.getModel();
                for (int ii = 0; ii < model.getRowCount(); ii++) {
                    final JLabel label = (JLabel) model.getValueAt(ii, 1);
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            label.setIcon(busyIcon);
                            busyIcon.setImageObserver(table);
                            table.revalidate();
                            table.repaint();
                        }
                    });
                    Requirement requirement = (Requirement) model.getValueAt(ii, 0);
                    final RequirementProvider.Status status = provider.validate(requirement);
                    requirement.setStatus(status);
                    if (status.getCode() == RequirementProvider.FAIL) {
                        result = FAIL;
                    } else if (OK.equals(result) && status.getCode() == RequirementProvider.WARN) {
                        result = WARN;
                    }

                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            switch (status.getCode()) {
                            case RequirementProvider.OK:
                                label.setIcon(okIcon);
                                break;
                            case RequirementProvider.WARN:
                                label.setIcon(warnIcon);
                                break;
                            default:
                                label.setIcon(failedIcon);
                            }
                            table.revalidate();
                            table.repaint();
                        }
                    });
                }
                return result;
            }
        });
        if (FAIL.equals(result)) {
            form.showErrorMessage(Installer.getString("requirements.message.failed"));
        } else if (WARN.equals(result)) {
            form.showWarningMessage(Installer.getString("requirements.message.warning"));
        } else {
            form.showInfoMessage(Installer.getString("requirements.message.ok"));
        }
        boolean valid = !result.equals(FAIL);
        setValid(valid);
        retryButton.setVisible(retryButton.isVisible() || !valid);
        retryButton.setEnabled(!valid);
    } catch (Exception e) {
        GuiDialogs.showError(e);
        setValid(false);
    } finally {
        setBusy(false);
    }
}

From source file:org.hibernate.search.demo.SearchDemo.java

private void initWidgets() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setDefaultLookAndFeelDecorated(true);

    BorderLayout borderLayout = new BorderLayout();
    getContentPane().setLayout(borderLayout);

    // the main table
    model = new DefaultTableModel(headers, 0) {
        public boolean isCellEditable(int row, int column) {
            // at the moment only allows the editing of the title
            return column == 2;
        }// www  .  j a  v a2 s  .com
    };
    modelListener = new TableModelListener() {
        public void tableChanged(TableModelEvent e) {
            int row = e.getFirstRow();
            int column = e.getColumn();
            TableModel model = (TableModel) e.getSource();
            Object data = model.getValueAt(row, column);
            EntityManager em = emf.createEntityManager();
            updateTitle((Long) model.getValueAt(row, 0), (String) data);
            log.info("new value: {}", data);
        }
    };
    model.addTableModelListener(modelListener);
    final JTable table = new JTable(model);

    table.setFont(new Font("Courier New", Font.PLAIN, 14));
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);

    // build  the controls
    JPanel controlPanel = new JPanel();
    controlPanel.setLayout(new FlowLayout());

    final JTextField searchField = new JTextField(30);
    controlPanel.add(searchField);

    JButton searchButton = new JButton("Search");
    searchButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {

            List<Product> products;

            try {
                products = search(searchField.getText());
            } catch (ParseException pe) {
                JOptionPane.showMessageDialog(null, pe.getMessage(), "alert", JOptionPane.ERROR_MESSAGE);
                return;
            }

            DefaultTableModel model = (DefaultTableModel) table.getModel();
            model.removeTableModelListener(modelListener);
            model.setRowCount(0);
            for (int i = 0; i < products.size(); i++) {
                Object[] data = new Object[headers.length];
                Product p = products.get(i);
                data[0] = p.getProductId();
                data[1] = p.getASIN();
                data[2] = p.getTitle();
                //data[3] = p.getDescription();
                String actors = "";
                for (Actor actor : p.getActors()) {
                    actors = actors + actor.getName() + ", ";
                }
                data[3] = actors.length() == 0 ? actors : actors.substring(0, actors.length() - 2);
                String categories = "";
                for (Category category : p.getCategories()) {
                    categories = categories + category.getName() + ", ";
                }
                data[4] = categories.length() == 0 ? categories
                        : categories.substring(0, categories.length() - 2);
                model.insertRow(i, data);
            }
            model.addTableModelListener(modelListener);
        }
    });
    controlPanel.add(searchButton);

    JButton indexButton = new JButton("Index");
    indexButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            index();
        }
    });
    controlPanel.add(indexButton);

    JButton purgeButton = new JButton("Purge");
    purgeButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            purge();
        }
    });
    controlPanel.add(purgeButton);

    getContentPane().add(controlPanel, BorderLayout.NORTH);
    getRootPane().setDefaultButton(searchButton);

    setSize(800, 200);
    setVisible(true);
}

From source file:org.ops4j.pax.idea.runner.forms.OsgiConfigEditorForm.java

private void retrieveSystemProperties(ConfigBean data) {
    TableModel model = m_systemProperties.getModel();
    Map<String, String> sysProps = new HashMap<String, String>();
    int rowCount = model.getRowCount();
    for (int row = 0; row < rowCount; row++) {
        String key = (String) model.getValueAt(row, 0);
        String value = (String) model.getValueAt(row, 1);
        sysProps.put(key, value);/*www .  j  a va2  s.  com*/
    }
    data.setSystemProperties(sysProps);
}

From source file:org.owasp.jbrofuzz.fuzz.io.Save.java

/**
 * <p>Method for obtaining the CSV output, given a table.</p>
 * <p>No "\n" is written at the end of the final line.</p>
 * // ww  w .j  a va2 s .  co m
 * @param The TableModel holding the data.
 * @return
 * <code>
 * 1,Plain Text,,
 * 2,URL UTF-8,graun,ge3dr
 * </code>
 * 
 * @author subere@uncon.org
 * @version 2.5
 * @since 2.5
 */
public static String getTableDataInCSVFormat(final TableModel inputTableModel) {

    final StringBuffer output = new StringBuffer();
    final int totalRows = inputTableModel.getRowCount();
    final int totalColumns = inputTableModel.getColumnCount();

    if (totalRows < 1) {
        return "";
    }

    for (int currentRow = 0; currentRow < totalRows; currentRow++) {

        for (int currentColumn = 0; currentColumn < totalColumns; currentColumn++) {
            output.append(inputTableModel.getValueAt(currentRow, currentColumn));
            // Append a ',' but not for the last value
            if (currentColumn != totalColumns - 1) {
                output.append(',');
            }
        }

        // Append a new line, but not for the last line
        if (currentRow != totalRows - 1) {
            output.append('\n');
        }

    }

    return output.toString();

}

From source file:org.owasp.jbrofuzz.fuzz.io.Save.java

/**
 * @author daemonmidi@gmail.com//  www  . j a  v  a 2  s. c  o m
 * @since version 2.5
 * @param inputTableModel
 * @return
 */
public static JSONArray getTableDataInJSON(final TableModel inputTableModel) {
    JSONArray tableData = new JSONArray();
    final int totalRows = inputTableModel.getRowCount() - 1;
    final int totalColumns = inputTableModel.getColumnCount() - 1;
    if (totalRows < 1) {
        return new JSONArray();
    }

    for (int currentRow = 0; currentRow < totalRows; currentRow++) {

        for (int currentColumn = 0; currentColumn < totalColumns - 1; currentColumn++) {
            String name = inputTableModel.getColumnName(currentColumn);
            String value = inputTableModel.getValueAt(currentColumn, currentRow).toString();
            String cellString = "{\"" + name + "\":\"" + value + "\"}";
            JSONObject cell;
            try {
                cell = new JSONObject(cellString);
                tableData.put(cell);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    return tableData;
}

From source file:org.pentaho.reporting.engine.classic.core.cache.CachingDataFactory.java

/**
 * Prints a table model to standard output.
 *
 * @param mod//from w  w w. j  av  a 2 s . co  m
 *          the model.
 */
public static void printTableModelContents(final TableModel mod) {
    if (mod == null) {
        throw new NullPointerException();
    }

    logger.debug("Tablemodel contains " + mod.getRowCount() + " rows."); //$NON-NLS-1$ //$NON-NLS-2$
    for (int i = 0; i < mod.getColumnCount(); i++) {
        logger.debug("Column: " + i + " Name = " + mod.getColumnName(i) + "; DataType = " //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
                + mod.getColumnClass(i));
    }

    logger.debug("Checking the data inside"); //$NON-NLS-1$
    for (int rows = 0; rows < mod.getRowCount(); rows++) {
        for (int i = 0; i < mod.getColumnCount(); i++) {
            final Object value = mod.getValueAt(rows, i);
            logger.debug("ValueAt (" + rows + ", " + i + ") is " + value); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
        }
    }
}

From source file:org.pentaho.reporting.engine.classic.core.function.formula.MultiValueQueryFunction.java

private Object performQuery(final ReportFormulaContext context, final String query, final String columnName,
        final int queryTimeout, final int queryLimit) throws EvaluationException {

    try {//from  ww  w  .  ja  v a2 s. c om
        final DataFactory dataFactory = context.getRuntime().getDataFactory();
        final TableModel tableModel = dataFactory.queryData(query,
                new QueryDataRowWrapper(context.getDataRow(), queryLimit, queryTimeout));
        if (tableModel == null) {
            return null;
        }
        final int columnCount = tableModel.getColumnCount();
        if (tableModel.getRowCount() == 0 || columnCount == 0) {
            return null;
        }

        for (int column = 0; column < columnCount; column++) {
            if (columnName == null || columnName.equals(tableModel.getColumnName(column))) {
                final ArrayList<Object> values = new ArrayList<Object>();
                int rowCount = tableModel.getRowCount();
                if (queryLimit > 0) {
                    rowCount = Math.min(queryLimit, tableModel.getRowCount());
                }
                for (int row = 0; row < rowCount; row++) {
                    values.add(tableModel.getValueAt(row, column));
                }
                return values.toArray();
            }
        }
        throw EvaluationException.getInstance(LibFormulaErrorValue.ERROR_UNEXPECTED_VALUE);
    } catch (EvaluationException e) {
        throw e;
    } catch (Exception e) {
        logger.warn("SingleValueQueryFunction: Failed to perform query", e);
        throw EvaluationException.getInstance(LibFormulaErrorValue.ERROR_UNEXPECTED_VALUE);
    }
}

From source file:org.pentaho.reporting.engine.classic.core.function.formula.SingleValueQueryFunction.java

private Object performQuery(final ReportFormulaContext context, final String query, final String column,
        final int queryTimeout) throws EvaluationException {

    try {/*from  www. j  a  va  2 s .c  o  m*/
        final DataFactory dataFactory = context.getRuntime().getDataFactory();
        final TableModel tableModel = dataFactory.queryData(query,
                new QueryDataRowWrapper(context.getDataRow(), 1, queryTimeout));
        if (tableModel == null) {
            return null;
        }

        final int columnCount = tableModel.getColumnCount();
        if (tableModel.getRowCount() == 0 || columnCount == 0) {
            return null;
        }
        if (column == null) {
            return tableModel.getValueAt(0, 0);
        }
        for (int i = 0; i < columnCount; i++) {
            if (column.equals(tableModel.getColumnName(i))) {
                return tableModel.getValueAt(0, i);
            }
        }
        throw EvaluationException.getInstance(LibFormulaErrorValue.ERROR_UNEXPECTED_VALUE);
    } catch (EvaluationException e) {
        throw e;
    } catch (Exception e) {
        SingleValueQueryFunction.logger.warn("SingleValueQueryFunction: Failed to perform query", e);
        throw EvaluationException.getInstance(LibFormulaErrorValue.ERROR_UNEXPECTED_VALUE);
    }
}

From source file:org.pentaho.reporting.engine.classic.core.function.sys.SingleValueQueryFunction.java

/**
 * Performs the query by collecting the data from the datarow and executing the query.
 *
 * @return the computed value.//w  w  w.  java  2s.co m
 */
private Object performQuery() {
    if (query == null) {
        return null;
    }
    try {
        final DataFactory dataFactory = getRuntime().getDataFactory();
        final String[] fields = getField();
        final int length = fields.length;
        final ParameterMapping[] mappings = new ParameterMapping[length];
        for (int i = 0; i < length; i++) {
            mappings[i] = new ParameterMapping(fields[i], fields[i]);
        }

        final QueryParametersDataRow params = new QueryParametersDataRow(getDataRow(), mappings);
        final TableModel tableModel = dataFactory.queryData(query,
                new QueryDataRowWrapper(params, 1, queryTimeout));
        if (tableModel == null) {
            return null;
        }
        final int columnCount = tableModel.getColumnCount();
        if (tableModel.getRowCount() == 0 || columnCount == 0) {
            return null;
        }
        if (resultColumn == null) {
            return tableModel.getValueAt(0, 0);
        }
        for (int i = 0; i < columnCount; i++) {
            if (resultColumn.equals(tableModel.getColumnName(i))) {
                return tableModel.getValueAt(0, i);
            }
        }
        // do nothing ..
    } catch (Exception e) {
        logger.warn("SingleValueQueryFunction: Failed to perform query", e);
    }
    return null;
}

From source file:org.pentaho.reporting.engine.classic.extensions.modules.mailer.MailProcessor.java

private static void processRecipients(final MailDefinition definition, final MimeMessage message,
        final DataFactory dataFactory, final DataRow parameterDataRow)
        throws ReportDataFactoryException, MessagingException {
    if (definition.getRecipientsQuery() != null
            && dataFactory.isQueryExecutable(definition.getRecipientsQuery(), parameterDataRow)) {
        final TableModel model = wrapWithParameters(
                dataFactory.queryData(definition.getRecipientsQuery(), parameterDataRow), parameterDataRow);

        for (int r = 0; r < model.getRowCount(); r++) {
            String address = null;
            String name = null;/*from  ww w .ja  v  a2 s  .c  om*/
            String type = "TO";
            if (model.getColumnCount() >= 3) {
                type = (String) model.getValueAt(0, 2);
            }
            if (model.getColumnCount() >= 2) {
                name = (String) model.getValueAt(0, 1);
            }
            if (model.getColumnCount() >= 1) {
                address = (String) model.getValueAt(0, 0);
            }
            if (address == null) {
                continue;
            }

            if (name == null) {
                message.addRecipient(parseType(type), new InternetAddress(address, true));
            } else {
                try {
                    message.addRecipient(parseType(type), new InternetAddress(address, name, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    // Should not happen - UTF-8 is safe to use
                    throw new MessagingException("Failed to encode recipient", e);
                }
            }
        }
    }
}