Example usage for javax.swing JTable getModel

List of usage examples for javax.swing JTable getModel

Introduction

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

Prototype

public TableModel getModel() 

Source Link

Document

Returns the TableModel that provides the data displayed by this JTable .

Usage

From source file:au.org.ala.delta.editor.ui.ActionSetsDialog.java

private DirectiveFile getSelectedFile() {
    JTable selectedTable = (JTable) ((JScrollPane) tabbedPane.getSelectedComponent()).getViewport().getView();

    int selected = selectedTable.getSelectedRow();

    DirectiveFile file = null;/*w  w w. j av a  2  s. c om*/
    if (selected >= 0) {
        // Convert view index to model index (we have a row sorter active).
        selected = selectedTable.convertRowIndexToModel(selected);
        file = ((DirectiveFileTableModel) selectedTable.getModel()).getFileAt(selected);
    }
    return file;
}

From source file:fll.subjective.SubjectiveFrame.java

/**
 * Show differences.//from w  w  w . j a v a2s . co m
 */
private void showDifferencesDialog(final Collection<SubjectiveScoreDifference> diffs) {
    final SubjectiveDiffTableModel model = new SubjectiveDiffTableModel(diffs);
    final JTable table = new JTable(model);
    table.setGridColor(Color.BLACK);

    table.addMouseListener(new MouseAdapter() {
        public void mouseClicked(final MouseEvent e) {
            if (e.getClickCount() == 2) {
                final JTable target = (JTable) e.getSource();
                final int row = target.getSelectedRow();

                final SubjectiveScoreDifference diff = model.getDiffForRow(row);

                // find correct table
                final String category = diff.getCategory();
                final JTable scoreTable = getTableForTitle(category);
                final int tabIndex = getTabIndexForCategory(category);
                getTabbedPane().setSelectedIndex(tabIndex);

                // get correct row and column
                final SubjectiveTableModel model = (SubjectiveTableModel) scoreTable.getModel();
                final int scoreRow = model.getRowForTeamAndJudge(diff.getTeamNumber(), diff.getJudge());
                final int scoreCol = model.getColForSubcategory(diff.getSubcategory());
                if (scoreRow == -1 || scoreCol == -1) {
                    throw new FLLRuntimeException(
                            "Internal error: Cannot find correct row and column for score difference: " + diff);
                }

                scoreTable.changeSelection(scoreRow, scoreCol, false, false);
            }
        }
    });

    final JDialog dialog = new JDialog(this, false);
    final Container cpane = dialog.getContentPane();
    cpane.setLayout(new BorderLayout());
    final JScrollPane tableScroller = new JScrollPane(table);
    cpane.add(tableScroller, BorderLayout.CENTER);

    dialog.pack();
    dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    dialog.setVisible(true);
}

From source file:com.smanempat.controller.ControllerEvaluation.java

public void showDataSetTest(JTable tableDataSetTesting, JTable tableTahunTesting, JLabel labelTotalDataModel)
        throws SQLException {
    int row;//from ww  w.  j a v  a 2  s  . com
    int transMinat;
    //modelEvaluation = new ModelEvaluation();
    tableModelDataSet2 = (DefaultTableModel) tableDataSetTesting.getModel();
    //tempArray = new ArrayList<String>();
    row = tableModelDataSet2.getRowCount();
    for (int i = 0; i < row; i++) {
        tableModelDataSet2.removeRow(0);
    }
    row = tableTahunTesting.getRowCount();
    boolean checkList;
    for (int i = 0; i < row; i++) {
        checkList = Boolean.valueOf("" + tableTahunTesting.getValueAt(i, 1));
        if (checkList == true) {
            dbConnection = new DbConnection();
            connect = dbConnection.connect();
            query = "SELECT * FROM siswa WHERE tahun_ajaran = ?";
            pstmt = connect.prepareStatement(query);
            pstmt.setString(1, tableTahunTesting.getValueAt(i, 0).toString());
            rs = pstmt.executeQuery();
            while (rs.next()) {
                String nis = rs.getString("nis");
                String nama = rs.getString("nama");
                String jenisKelamin = rs.getString("jenis_kelamin");
                String nilaiUN = rs.getString("nilai_un");
                double meanUN = Double.parseDouble(nilaiUN) / 4;
                String ptBindo = rs.getString("pt_bhs_indonesia");
                String ptMtk = rs.getString("pt_matematika");
                String ptBing = rs.getString("pt_bhs_inggris");
                String ptIpa = rs.getString("pt_ipa");
                double meanPt = (Double.parseDouble(ptBindo) + Double.parseDouble(ptMtk)
                        + Double.parseDouble(ptBing) + Double.parseDouble(ptIpa)) / 4;
                String minat = rs.getString("minat");
                if (minat.equals("IPA")) {
                    transMinat = 1;
                } else {
                    transMinat = 0;
                }
                jurusan = rs.getString("jurusan");
                Object tableContent[] = { nis, nilaiUN, meanUN, ptBindo, ptMtk, ptBing, ptIpa, meanPt, minat,
                        transMinat };

                tableModelDataSet2.addRow(tableContent);
            }
        }
        tableDataSetTesting.setModel(tableModelDataSet2);
        labelTotalDataModel.setText(tableDataSetTesting.getRowCount() + " Data");
    }
}

From source file:gdt.jgui.entity.fields.JFieldsEditor.java

private String getEditCellLocator() {
    try {/*from   w w w.j  a  va  2  s  .  c om*/
        save();
        String locator$ = getLocator();
        if (entihome$ != null)
            locator$ = Locator.append(locator$, Entigrator.ENTIHOME, entihome$);
        if (entityKey$ != null)
            locator$ = Locator.append(locator$, EntityHandler.ENTITY_KEY, entityKey$);
        JTable table = (JTable) scrollPane.getViewport().getView();
        int x = table.getEditingRow();
        int y = table.getEditingColumn();
        String cellField$ = CELL_FIELD_NAME;
        if (y == 1)
            cellField$ = CELL_FIELD_VALUE;
        TableModel model = table.getModel();
        text$ = (String) model.getValueAt(x, y);
        String fieldName$ = (String) model.getValueAt(x, 0);
        locator$ = Locator.append(locator$, JTextEditor.TEXT, text$);
        locator$ = Locator.append(locator$, CELL_FIELD, cellField$);
        locator$ = Locator.append(locator$, CELL_FIELD_NAME, fieldName$);
        if (requesterResponseLocator$ != null)
            locator$ = Locator.append(locator$, JRequester.REQUESTER_RESPONSE_LOCATOR,
                    requesterResponseLocator$);
        locator$ = Locator.append(locator$, BaseHandler.HANDLER_METHOD, JFacetOpenItem.METHOD_RESPONSE);
        // System.out.println("FieldsEditor:getEditCellLocator:END:"+locator$);
        return locator$;
    } catch (Exception e) {
        LOGGER.severe(e.toString());
        return null;
    }
}

From source file:coolmap.application.widget.impl.WidgetUserGroup.java

private void init() {

    table.getTableHeader().setReorderingAllowed(false);
    table.setAutoCreateRowSorter(true);//from   w w  w  . ja v a  2s .c o  m
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                    column);
            if (isSelected) {
                return label;
            }

            if (column == 1) {
                try {
                    label.setBackground(
                            nodeColor.get(table.getModel().getValueAt(table.convertRowIndexToModel(row), 0)));
                } catch (Exception e) {

                }
            } else {
                label.setBackground(UI.colorWhite);
            }

            return label;
        }

    });
    //Need a search box as well.

    //
    getContentPane().setLayout(new BorderLayout());

    //
    getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    JToolBar t = new JToolBar();
    getContentPane().add(t, BorderLayout.NORTH);
    t.setFloatable(false);

    try {
        //also add an action to add group nodes
        JMenuItem item = new JMenuItem("selected row nodes");
        item.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                CoolMapObject o = CoolMapMaster.getActiveCoolMapObject();
                if (o == null) {
                    return;
                }

                ArrayList<Range<Integer>> selected = o.getCoolMapView().getSelectedRows();
                ArrayList<VNode> selectedNodes = new ArrayList<>();

                for (Range<Integer> r : selected) {
                    for (int i = r.lowerEndpoint(); i < r.upperEndpoint(); i++) {
                        selectedNodes.add(o.getViewNodeRow(i));
                    }
                }

                createNewGroup(selectedNodes);

                //create a group
            }
        });
        WidgetMaster.getViewport().addPopupMenuItem("Create group", item, false);

        item = new JMenuItem("selected column nodes");
        item.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                CoolMapObject o = CoolMapMaster.getActiveCoolMapObject();
                if (o == null) {
                    return;
                }

                ArrayList<Range<Integer>> selected = o.getCoolMapView().getSelectedColumns();
                ArrayList<VNode> selectedNodes = new ArrayList<>();

                for (Range<Integer> r : selected) {
                    for (int i = r.lowerEndpoint(); i < r.upperEndpoint(); i++) {
                        selectedNodes.add(o.getViewNodeColumn(i));
                    }
                }

                createNewGroup(selectedNodes);

            }
        });
        WidgetMaster.getViewport().addPopupMenuItem("Create group", item, false);
    } catch (Exception e) {
        //
        //Error handling.
    }

}

From source file:gdt.jgui.tool.JEntityEditor.java

private void save() {
    try {/*www . j  a v  a  2s  . c om*/
        int eCnt = tabbedPane.getComponentCount();
        Sack candidate = new Sack();
        String element$;
        JScrollPane scrollPane;
        JTable table;
        int rCnt;
        Core row;
        TableModel model;
        for (int i = 0; i < eCnt; i++) {
            element$ = tabbedPane.getTitleAt(i);
            candidate.createElement(element$);
            scrollPane = (JScrollPane) tabbedPane.getComponentAt(i);
            table = (JTable) scrollPane.getViewport().getView();
            rCnt = table.getRowCount();
            model = table.getModel();
            for (int j = 0; j < rCnt; j++) {
                row = new Core((String) model.getValueAt(j, 0), (String) model.getValueAt(j, 1),
                        (String) model.getValueAt(j, 2));
                if ("attributes".equals(element$))
                    candidate.putAttribute(row);
                else
                    candidate.putElementItem(element$, row);
            }
        }
        candidate.setKey(entityKey$);
        candidate.saveXML(entihome$ + "/" + Entigrator.ENTITY_BASE + "/data/" + entityKey$);
    } catch (Exception e) {
        LOGGER.severe(e.toString());
    }
}

From source file:canreg.client.gui.analysis.FrequenciesByYearInternalFrame.java

/**
 *
 * @param offset/* w w w . ja  va  2 s .  c om*/
 * @param evt
 */
public void showPopUpMenu(int offset, java.awt.event.MouseEvent evt) {
    JTable target = (JTable) evt.getSource();
    int rowNumber = target.rowAtPoint(new Point(evt.getX(), evt.getY()));
    rowNumber = target.convertRowIndexToModel(rowNumber);

    JPopupMenu jpm = new JPopupMenu();
    jpm.add(java.util.ResourceBundle
            .getBundle("canreg/client/gui/analysis/resources/FrequenciesByYearInternalFrame")
            .getString("SHOW_IN_BROWSER"));
    TableModel tableModel = target.getModel();
    // resultTable.get
    // jpm.add("Column " + rowNumber +" " + tableColumnModel.getColumn(tableColumnModel.getColumnIndexAtX(evt.getX())).getHeaderValue());
    int year = Integer.parseInt((String) tableModel.getValueAt(rowNumber, 0));

    String filterString = "INCID >= '" + year * 10000 + "' AND INCID <'" + (year + 1) * 10000 + "'";

    for (DatabaseVariablesListElement dvle : chosenVariables) {
        int columnNumber = tableColumnModel
                .getColumnIndex(canreg.common.Tools.toUpperCaseStandardized(dvle.getDatabaseVariableName()));
        String value = tableModel.getValueAt(rowNumber, columnNumber).toString();
        filterString += " AND " + canreg.common.Tools.toUpperCaseStandardized(dvle.getDatabaseVariableName())
                + " = " + dvle.getSQLqueryFormat(value);
    }
    DatabaseFilter filter = new DatabaseFilter();
    filter.setFilterString(filterString);
    Logger.getLogger(FrequenciesByYearInternalFrame.class.getName()).log(Level.INFO, "FilterString: {0}",
            filterString);
    try {
        tableDatadescriptionPopUp = canreg.client.CanRegClientApp.getApplication()
                .getDistributedTableDescription(filter, rangeFilterPanel.getSelectedTable());
        Object[][] rows = canreg.client.CanRegClientApp.getApplication().retrieveRows(
                tableDatadescriptionPopUp.getResultSetID(), 0, MAX_ENTRIES_DISPLAYED_ON_RIGHT_CLICK);
        String[] variableNames = tableDatadescriptionPopUp.getColumnNames();
        for (Object[] row : rows) {
            String line = "";
            int i = 0;
            for (Object obj : row) {
                if (obj != null) {
                    line += variableNames[i] + ": " + obj.toString() + ", ";
                }
                i++;
            }
            jpm.add(line);
        }
    } catch (SQLException ex) {
        Logger.getLogger(FrequenciesByYearInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (RemoteException ex) {
        Logger.getLogger(FrequenciesByYearInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SecurityException ex) {
        Logger.getLogger(FrequenciesByYearInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DistributedTableDescriptionException ex) {
        Logger.getLogger(FrequenciesByYearInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnknownTableException ex) {
        Logger.getLogger(FrequenciesByYearInternalFrame.class.getName()).log(Level.SEVERE, null, ex);
    }

    int cases = (Integer) tableModel.getValueAt(rowNumber, tableColumnModel.getColumnIndex("CASES"));
    if (MAX_ENTRIES_DISPLAYED_ON_RIGHT_CLICK < cases) {
        jpm.add("...");
    }
    MenuItem menuItem = new MenuItem();

    jpm.show(target, evt.getX(), evt.getY());
}

From source file:gdt.jgui.tool.JEntityEditor.java

private String getEditCellLocator() {
    try {/*ww w.  j  a va  2 s.  c  o m*/
        save();
        JTextEditor textEditor = new JTextEditor();
        String locator$ = textEditor.getLocator();
        locator$ = Locator.merge(getLocator(), locator$);
        JScrollPane scrollPane = (JScrollPane) tabbedPane.getSelectedComponent();
        JTable table = (JTable) scrollPane.getViewport().getView();
        int i = tabbedPane.getSelectedIndex();
        String element$ = tabbedPane.getTitleAt(i);
        int x = table.getEditingRow();
        int y = table.getEditingColumn();
        String cellField$ = CELL_FIELD_TYPE;
        if (y == 1)
            cellField$ = CELL_FIELD_NAME;
        else if (y == 2)
            cellField$ = CELL_FIELD_VALUE;
        TableModel model = table.getModel();
        String text$ = (String) model.getValueAt(x, y);
        text$ = Locator.compressText(text$);
        locator$ = Locator.append(locator$, JTextEditor.IS_BASE64, Locator.LOCATOR_TRUE);
        String coreName$ = (String) model.getValueAt(x, 1);
        locator$ = Locator.append(locator$, JTextEditor.TEXT, text$);
        locator$ = Locator.append(locator$, ELEMENT, element$);
        locator$ = Locator.append(locator$, CELL_FIELD, cellField$);
        locator$ = Locator.append(locator$, CORE_NAME, coreName$);
        locator$ = Locator.append(locator$, JRequester.REQUESTER_ACTION, ACTION_EDIT_CELL);
        locator$ = Locator.append(locator$, Locator.LOCATOR_TITLE, "Edit item");
        locator$ = Locator.append(locator$, BaseHandler.HANDLER_CLASS, JTextEditor.class.getName());
        return locator$;
    } catch (Exception e) {
        LOGGER.severe(e.toString());
        return null;
    }
}

From source file:SortableTable.java

/**
 * Returns the renderer component.// w  ww .j a  va2 s .c  o m
 *
 * @param table      the table.
 * @param value      the value.
 * @param isSelected selected?
 * @param hasFocus   focussed?
 * @param row        the row.
 * @param column     the column.
 * @return the renderer.
 */
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected,
        final boolean hasFocus, final int row, final int column) {

    if (table == null) {
        throw new NullPointerException("Table must not be null.");
    }

    final JComponent component;
    final SortableTableModel model = (SortableTableModel) table.getModel();
    final int cc = table.convertColumnIndexToModel(column);
    final boolean isSorting = (model.getSortingColumn() == cc);
    final boolean isAscending = model.isAscending();

    final JTableHeader header = table.getTableHeader();
    final boolean isPressed = (cc == this.pressedColumn);

    if (this.useLabels) {
        final JLabel label = getRendererLabel(isSorting, isAscending);
        label.setText((value == null) ? "" : value.toString());
        component = label;
    } else {
        final JButton button = getRendererButton(isSorting, isAscending);
        button.setText((value == null) ? "" : value.toString());
        button.getModel().setPressed(isPressed);
        button.getModel().setArmed(isPressed);
        component = button;
    }

    if (header != null) {
        component.setForeground(header.getForeground());
        component.setBackground(header.getBackground());
        component.setFont(header.getFont());
    }
    return component;
}

From source file:com.github.lindenb.jvarkit.tools.bamviewgui.BamFileRef.java

BamFrame(List<BamFileRef> BamFileRefs) {
    super((JFrame) null, "Bam View (" + BamFileRefs.size() + " files)", ModalityType.APPLICATION_MODAL);
    this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    this.BamFileRefs = BamFileRefs;

    addWindowListener(new WindowAdapter() {

        @Override//from w  w w .  j a v a2 s .  c  o  m
        public void windowOpened(WindowEvent e) {
            removeWindowListener(this);
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
            d.width -= 150;
            d.height -= 150;
            for (BamFileRef vfr : BamFrame.this.BamFileRefs) {
                LOG.info("Reading " + vfr.bamFile);
                int w = (int) (d.width * 0.8);
                int h = (int) (d.height * 0.8);
                BamInternalFrame iFrame = new BamInternalFrame(vfr);
                iFrame.setBounds(Math.max((int) ((d.width - w) * Math.random()), 0),
                        Math.max((int) ((d.height - h) * Math.random()), 0), w, h);
                desktopPane.add(iFrame);
                BamInternalFrames.add(iFrame);
                iFrame.setVisible(true);
                iFrame.jTable.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        if (e.getClickCount() == 2) {
                            JTable t = (JTable) e.getSource();
                            int row = t.getSelectedRow();
                            if (row == -1)
                                return;
                            BamTableModel tm = (BamTableModel) t.getModel();
                            showIgv(tm.getValueAt(row, 0), tm.getValueAt(row, 1));
                        }
                    }
                });
            }
            reloadFrameContent();
        }
    });

    addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            doMenuClose();
        }
    });
    JMenuBar bar = new JMenuBar();
    setJMenuBar(bar);

    JMenu menu = new JMenu("File");
    bar.add(menu);
    menu.add(new AbstractAction("Quit") {
        @Override
        public void actionPerformed(ActionEvent e) {
            doMenuClose();
        }
    });

    menu = new JMenu("Flags");
    bar.add(menu);
    for (SamFlag flag : SamFlag.values()) {
        JCheckBox cbox = new JCheckBox("Require " + flag);
        requiredFlags.add(cbox);
        menu.add(cbox);
    }
    menu.add(new JSeparator());
    for (SamFlag flag : SamFlag.values()) {
        JCheckBox cbox = new JCheckBox("Filter out " + flag);
        filteringFlags.add(cbox);
        menu.add(cbox);
    }

    JPanel contentPane = new JPanel(new BorderLayout(5, 5));
    setContentPane(contentPane);
    this.desktopPane = new JDesktopPane();
    contentPane.add(this.desktopPane, BorderLayout.CENTER);

    JPanel top = new JPanel(new FlowLayout(FlowLayout.LEADING));
    contentPane.add(top, BorderLayout.NORTH);

    JLabel lbl = new JLabel("Max Rows:", JLabel.LEADING);
    JSpinner spinner = new JSpinner(this.numFetchModel = new SpinnerNumberModel(100, 1, 10000, 10));
    lbl.setLabelFor(spinner);
    top.add(lbl);
    top.add(spinner);

    lbl = new JLabel("Timeout (secs):", JLabel.LEADING);
    spinner = new JSpinner(this.numSecondsModel = new SpinnerNumberModel(2, 1, 10000, 1));
    lbl.setLabelFor(spinner);
    top.add(lbl);
    top.add(spinner);

    //lbl=new JLabel("JEXL:",JLabel.LEADING);
    /*jexlField=new JTextField(20);
    lbl.setLabelFor(jexlField);
            
    top.add(lbl);
    top.add(jexlField);*/

    lbl = new JLabel("Region:", JLabel.LEADING);
    selectRgnField = new JTextField(20);
    lbl.setLabelFor(selectRgnField);
    AbstractAction action = new AbstractAction("Select") {
        private static final long serialVersionUID = 1L;

        @Override
        public void actionPerformed(ActionEvent a) {
            if (
            /* (jexlField.getText().trim().isEmpty() || parseJex(jexlField.getText().trim())!=null) && */
            (selectRgnField.getText().trim().isEmpty() || parseOne(selectRgnField.getText()) != null)) {
                reloadFrameContent();
            } else {
                LOG.info("Bad input " + selectRgnField.getText());
            }
        }
    };
    selectRgnField.addActionListener(action);
    //jexlField.addActionListener(action);

    top.add(lbl);
    top.add(selectRgnField);
    top.add(new JButton(action));

}