Example usage for javax.swing JTable setModel

List of usage examples for javax.swing JTable setModel

Introduction

In this page you can find the example usage for javax.swing JTable setModel.

Prototype

@BeanProperty(description = "The model that is the source of the data for this view.")
public void setModel(final TableModel dataModel) 

Source Link

Document

Sets the data model for this table to dataModel and registers with it for listener notifications from the new data model.

Usage

From source file:net.sourceforge.atunes.kernel.controllers.stats.StatsDialogController.java

private void setTable(JTable table, Object[] headers, Object[][] content) {
    table.setModel(new DefaultTableModel(content, headers));
    table.getColumnModel().getColumn(0).setPreferredWidth(420);
    table.getColumnModel().getColumn(0).setWidth(table.getColumnModel().getColumn(0).getWidth());
    table.getColumnModel().getColumn(2).setPreferredWidth(30);
    table.getColumnModel().getColumn(2).setWidth(table.getColumnModel().getColumn(2).getWidth());
    table.getColumnModel().getColumn(1).setCellRenderer(new SubstanceDefaultTableCellRenderer() {
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                    column);//from  w ww  .java 2 s .  c om
            l.setHorizontalAlignment(SwingConstants.RIGHT);
            return l;
        }
    });
    table.getColumnModel().getColumn(2).setCellRenderer(new SubstanceDefaultTableCellRenderer() {
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel l = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                    column);
            l.setHorizontalAlignment(SwingConstants.RIGHT);
            return l;
        }
    });
}

From source file:edu.ku.brc.specify.plugins.sgr.SGRResultsDisplay.java

/**
 * From http://www.pikopong.com/blog/2008/08/13/auto-resize-jtable-column-width/
 * //w  w w.  j av a 2s  .  c o  m
 * @param table
 * @param model
 * @return
 */
private JTable autoResizeColWidth(JTable table, DefaultTableModel model) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setModel(model);

    int margin = 5;

    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();

        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }

        Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0,
                0);

        width = comp.getPreferredSize().width;

        // Get maximum width of column data
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
                    r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

        // Set the width
        col.setPreferredWidth(width);
    }

    ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
            .setHorizontalAlignment(SwingConstants.LEFT);

    // table.setAutoCreateRowSorter(true);
    //table.getTableHeader().setReorderingAllowed(false);

    return table;
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.singlecell.SingleCellStatisticsController.java

/**
 * Show Summary Statistics in correspondent table
 *
 * @param analysisGroup/*from w  w w  .j  a  va2  s  . co  m*/
 */
private void showSummary(SingleCellAnalysisGroup singleCellAnalysisGroup) {
    singleCellAnalysisController.getAnalysisPanel().getCurrentGroupName()
            .setText(singleCellAnalysisGroup.getGroupName());
    // set model and cell renderer for statistics summary table
    SingleCellStatSummaryTableModel statisticalSummaryTableModel = new SingleCellStatSummaryTableModel(
            singleCellAnalysisGroup);
    JTable statisticalSummaryTable = singleCellAnalysisController.getAnalysisPanel().getStatTable();
    statisticalSummaryTable.setModel(statisticalSummaryTableModel);
    for (int i = 1; i < statisticalSummaryTable.getColumnCount(); i++) {
        statisticalSummaryTable.getColumnModel().getColumn(i)
                .setCellRenderer(new FormatRenderer(new DecimalFormat("#.####"), SwingConstants.CENTER));
    }
    statisticalSummaryTable.getTableHeader().setDefaultRenderer(new TableHeaderRenderer(SwingConstants.RIGHT));
}

From source file:be.ugent.maf.cellmissy.gui.controller.analysis.singlecell.SingleCellStatisticsController.java

/**
 * Show p-values in correspondent table//from w  w w .j a va 2  s  .  co  m
 *
 * @param analysisGroup
 */
private void showPValues(SingleCellAnalysisGroup singleCellAnalysisGroup, boolean isAdjusted) {
    String statisticalTestName = singleCellAnalysisController.getAnalysisPanel().getStatTestComboBox()
            .getSelectedItem().toString();
    SingleCellPValuesTableModel pValuesTableModel = new SingleCellPValuesTableModel(singleCellAnalysisGroup,
            isAdjusted);
    JTable pValuesTable = singleCellAnalysisController.getAnalysisPanel().getComparisonTable();
    pValuesTable.setModel(pValuesTableModel);
    Double selectedSignLevel = (Double) singleCellAnalysisController.getAnalysisPanel().getSignLevelComboBox()
            .getSelectedItem();
    // detect significances with selected alpha level
    singleCellStatisticsAnalyzer.detectSignificance(singleCellAnalysisGroup, statisticalTestName,
            selectedSignLevel, isAdjusted);
    boolean[][] significances = singleCellAnalysisGroup.getSignificances();
    for (int i = 1; i < pValuesTable.getColumnCount(); i++) {
        pValuesTable.getColumnModel().getColumn(i)
                .setCellRenderer(new PValuesTableRenderer(new DecimalFormat("#.####"), significances));
    }
    pValuesTable.getTableHeader().setDefaultRenderer(new TableHeaderRenderer(SwingConstants.RIGHT));
}

From source file:edu.harvard.mcz.imagecapture.ui.ButtonEditor.java

@Override
public void actionPerformed(ActionEvent e) {

    // Action might not be event_button_pressed on all systems.
    log.debug("Button event actionCommand: " + e.getActionCommand());
    if (e.getActionCommand().equals(EVENT_PRESSED)) {
        // Event is a click on the cell
        // Identify the row that was clicked on.
        JTable table = (JTable) ((JButton) e.getSource()).getParent();
        log.debug(e.getSource());/*from  w  w  w.  j  a v  a 2 s.  c  o m*/
        log.debug(table);
        int row = table.getEditingRow();
        // Stop editing - note, we need to have gotten e.getSource.getParent and getEditingRow first.
        fireEditingStopped(); //Make the renderer reappear.
        Singleton.getSingletonInstance().getMainFrame()
                .setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        switch (formToOpen) {
        case OPEN_SPECIMEN_DETAILS:
            // Load the selected specimen record from its ID (the data value behind the button).
            //SpecimenLifeCycle sls = new SpecimenLifeCycle();
            //Specimen specimen = sls.findById((Long)targetId);
            //if (specimen!=null) {
            if (targetId != null) {
                // a specimen with this ID exists, bring up the details editor.
                try {
                    //SpecimenControler sc = new SpecimenControler(specimen);
                    if (((Specimen) targetId).getSpecimenId() != null) {
                        if (((Specimen) targetId).isStateDone()) {
                            // Specimens in state_done are no longer editable
                            JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                    "This Specimen record has been migrated and can no longer be edited here ["
                                            + ((Specimen) targetId).getLoadFlags()
                                            + "].\nSee: http://mczbase.mcz.harvard.edu/guid/MCZ:Ent:"
                                            + ((Specimen) targetId).getCatNum(),
                                    "Migrated Specimen", JOptionPane.WARNING_MESSAGE);
                        } else {
                            // Specimen is still editable
                            if (table != null) {
                                // Pass the specimen object for the row, the table model, and the row number on to the specimen controler.
                                try {
                                    SpecimenControler sc = new SpecimenControler((Specimen) targetId,
                                            (SpecimenListTableModel) table.getModel(), table, row);
                                    if (table.getParent().getParent().getParent().getParent()
                                            .getClass() == SpecimenBrowser.class) {
                                        sc.addListener((DataChangeListener) table.getParent());
                                    } else {
                                        Component x = table;
                                        boolean done = false;
                                        while (!done) {
                                            log.debug(x.getParent());
                                            x = x.getParent();
                                            if (x.getClass() == SpecimenBrowser.class) {
                                                sc.addListener((DataChangeListener) x);
                                                done = true;
                                            }
                                        }
                                    }
                                    sc.displayInEditor();
                                } catch (java.lang.ClassCastException eNotSp) {
                                    // Request isn't coming from a SpecimenListTableModel
                                    // View just the specimen record.
                                    SpecimenControler sc = new SpecimenControler((Specimen) targetId);
                                    sc.displayInEditor();
                                }
                            } else {
                                log.debug(e.getSource());
                                //SpecimenControler sc = new SpecimenControler((Specimen)targetId);
                                //sc.displayInEditor();
                            }
                        }
                    } else {
                        log.debug("User clicked on table row containing a new Specimen()");
                        JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                                "No Specimen for this image", "Load Specimen Failed",
                                JOptionPane.WARNING_MESSAGE);
                    }
                } catch (NoSuchRecordException e1) {
                    log.error("Tested for specimen!=null, but SpecimenControler threw null specimen exception");
                    log.error(e1);
                }
            } else {
                log.debug("No matches found to specimen id=" + targetId);
                // TODO: Create new specimen record and bring up dialog
                JOptionPane.showMessageDialog(Singleton.getSingletonInstance().getMainFrame(),
                        "No specimen record.");
            }
            break;
        case OPEN_TEMPLATE:
            // Load the selected specimen record from its ID (the data value behind the button).
            try {
                // a template with this targetID exists, display it.
                ((PositionTemplateEditor) parentComponent).setTemplate((String) targetId);
            } catch (NoSuchTemplateException e1) {
                log.error("No such template on button press on a template in list.");
                log.error(e1);
                log.trace(e1);
            }

            break;
        case OPEN_USER:
            //TODO: tie to user
            log.debug("Open user");
            ((UserListBrowser) parentComponent).getEditUserPanel().setUser((Users) targetId);
            break;
        case OPEN_SPECIMEN_VERBATIM:
            log.debug("Open Verbatim Transcription");
            SpecimenLifeCycle sls = new SpecimenLifeCycle();
            List<Specimen> toTranscribe = sls.findForVerbatim(((GenusSpeciesCount) targetId).getGenus(),
                    ((GenusSpeciesCount) targetId).getSpecificEpithet(), WorkFlowStatus.STAGE_1);
            log.debug(toTranscribe.size());
            SpecimenListTableModel stm = new SpecimenListTableModel(toTranscribe);
            JTable stable = new JTable();
            stable.setModel(stm);
            SpecimenControler verbCont;
            try {
                verbCont = new SpecimenControler(toTranscribe.get(0), stm, stable, 0);
                VerbatimCaptureDialog dialog = new VerbatimCaptureDialog(toTranscribe.get(0), verbCont);
                dialog.setVisible(true);
            } catch (NoSuchRecordException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            break;
        case OPEN_VERBATIM_CLASSIFY:
            log.debug("Open Verbatim Classify dialog");
            try {
                VerbatimClassifyDialog dialog = new VerbatimClassifyDialog(
                        (VerbatimCount) table.getModel().getValueAt(row, 0));
                dialog.setVisible(true);
            } catch (ClassCastException e1) {
                log.error(e1.getMessage(), e1);
            }
            break;
        case ACTION_CANCEL_JOB:
            log.debug("Action Cancel requested on job " + targetId);
            Singleton.getSingletonInstance().getJobList().getJobAt((Integer) targetId).cancel();
            break;
        case OPEN_SPECIMENPARTATTRIBUTES:
            SpecimenPartAttributeDialog attrDialog = new SpecimenPartAttributeDialog((SpecimenPart) targetId);
            attrDialog.setVisible(true);
            break;
        }
        Singleton.getSingletonInstance().getMainFrame()
                .setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        System.gc();
    }
}

From source file:net.sourceforge.atunes.kernel.modules.statistics.StatsDialogController.java

/**
 * Sets the table./*from w ww  .  jav a2 s.c om*/
 * 
 * @param table
 *            the table
 * @param headers
 *            the headers
 * @param content
 *            the content
 */
private void setTable(final JTable table, final Object[] headers, final Object[][] content) {
    table.setModel(new StatsDialogDefaultTableModel(content, headers));
    table.getColumnModel().getColumn(0).setPreferredWidth(420);
    table.getColumnModel().getColumn(0).setWidth(table.getColumnModel().getColumn(0).getWidth());
    table.getColumnModel().getColumn(0).setCellRenderer(this.lookAndFeelManager.getCurrentLookAndFeel()
            .getTableCellRenderer(new SwingOrientationTableCellRendererCode(this.controlsBuilder)));
    table.getColumnModel().getColumn(2).setPreferredWidth(30);
    table.getColumnModel().getColumn(2).setWidth(table.getColumnModel().getColumn(2).getWidth());

    table.getColumnModel().getColumn(1).setCellRenderer(this.lookAndFeelManager.getCurrentLookAndFeel()
            .getTableCellRenderer(new RightAlignmentTableCellRendererCode()));
    table.getColumnModel().getColumn(2).setCellRenderer(this.lookAndFeelManager.getCurrentLookAndFeel()
            .getTableCellRenderer(new RightAlignmentTableCellRendererCode()));
}

From source file:com.sec.ose.osi.ui.frm.main.report.JPanBillOfMaterials.java

public void setCurrentProject(String projectName) {
    log.debug("--------------JPanBOM.setCurrentProject(), projectName:" + projectName);

    JTable bomTable = this.getJTableBOM();

    if (projectName == null) {
        BOMTableModel model = oBOMTableModelMgr.getDeaultBOMTableModel();
        bomTable.setModel(model);
        model.setColumnWidth(bomTable);/*w  w  w . ja v a2s .  c om*/
        return;
    }

    BOMTableModel model = oBOMTableModelMgr.getBOMTableModel(projectName, this.getJCheckBoxCheckAll());
    bomTable.setModel(model);
    model.setColumnWidth(bomTable);
}

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

    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);// w w  w  . j  a v a  2  s .  c om
                } 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:com.willwinder.universalgcodesender.uielements.panels.ControllerProcessorSettingsPanel.java

private JTable initCustomRemoverTable(JTable table) {
    final String[] columnNames = { Localization.getString("settings.processors.enabled"),
            Localization.getString("PatternRemover") };

    final Class[] columnTypes = { Boolean.class, String.class };

    DefaultTableModel model = new DefaultTableModel(null, columnNames) {
        @Override//from w  w  w  . j  av  a2s  .  com
        public Class<?> getColumnClass(int idx) {
            return columnTypes[idx];
        }
    };

    table.setModel(model);
    table.getTableHeader().setReorderingAllowed(false);
    table.getModel().addTableModelListener((TableModelEvent e) -> change());

    return table;
}

From source file:modnlp.capte.AlignmentInterfaceWS.java

public JTable autoResizeColWidth(JTable table, DefaultTableModel model) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setModel(model);

    int margin = 5;

    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        // Get width of column header
        TableCellRenderer renderer = col.getHeaderRenderer();

        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }/*w w  w. j a va2  s.c om*/

        Component comp = renderer.getTableCellRendererComponent(table, col.getHeaderValue(), false, false, 0,
                0);

        width = comp.getPreferredSize().width;

        // Get maximum width of column data
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            comp = renderer.getTableCellRendererComponent(table, table.getValueAt(r, vColIndex), false, false,
                    r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

        // Set the width
        col.setPreferredWidth(width);
    }

    ((DefaultTableCellRenderer) table.getTableHeader().getDefaultRenderer())
            .setHorizontalAlignment(SwingConstants.LEFT);

    // table.setAutoCreateRowSorter(true);
    table.getTableHeader().setReorderingAllowed(false);

    return table;
}