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:org.nuclos.client.ui.collect.component.AbstractCollectableComponent.java

public static void setBackgroundColor(Component cellRendererComponent, JTable tbl, Object oValue,
        boolean bSelected, boolean bHasFocus, int iRow, int iColumn) {
    cellRendererComponent.setBackground(bSelected ? tbl.getSelectionBackground()
            : iRow % 2 == 0 ? tbl.getBackground() : NuclosThemeSettings.BACKGROUND_PANEL);
    cellRendererComponent.setForeground(bSelected ? tbl.getSelectionForeground() : tbl.getForeground());

    final TableModel tm;
    final int adjustColIndex;
    if (tbl instanceof FixedColumnRowHeader.HeaderTable
            && ((FixedColumnRowHeader.HeaderTable) tbl).getExternalTable() != null) {
        tm = ((FixedColumnRowHeader.HeaderTable) tbl).getExternalTable().getModel();
        adjustColIndex = FixedRowIndicatorTableModel.ROWMARKERCOLUMN_COUNT;
    } else {/*from w  w w .j  a va  2  s . com*/
        tm = tbl.getModel();
        adjustColIndex = 0;
    }

    // check whether the data of the component is readable for current user, by asking the security agent of the actual field
    if (tm instanceof SortableCollectableTableModel<?>) {
        final SortableCollectableTableModel<Collectable> tblModel = (SortableCollectableTableModel<Collectable>) tm;
        if (tblModel.getRowCount() > iRow) {
            final Collectable clct = tblModel.getCollectable(iRow);
            final Integer iTColumn = tbl.getColumnModel().getColumn(iColumn).getModelIndex() - adjustColIndex;
            final CollectableEntityField clctef = tblModel.getCollectableEntityField(iTColumn);
            if (clctef == null) {
                throw new NullPointerException("getTableCellRendererComponent failed to find field: " + clct
                        + " tm index " + iTColumn);
            }

            boolean isEnabled = true;
            if (!clctef.isNullable() && isNull(oValue)) {
                cellRendererComponent.setBackground(getMandatoryColor());
                cellRendererComponent.setForeground(tbl.getForeground());
            } else {
                //               if (clct.getId() == null) {
                //                  cellRendererComponent.setBackground(tbl.getBackground());
                //                  cellRendererComponent.setForeground(tbl.getForeground());
                //               } else {
                if (tbl instanceof SubForm.SubFormTable) {
                    SubFormTable subformtable = (SubForm.SubFormTable) tbl;
                    Column subformcolumn = subformtable.getSubForm().getColumn(clctef.getName());
                    if (subformcolumn != null && !subformcolumn.isEnabled()) {
                        isEnabled = false;
                        if (bSelected) {
                            cellRendererComponent
                                    .setBackground(NuclosThemeSettings.BACKGROUND_INACTIVESELECTEDCOLUMN);
                        } else {
                            cellRendererComponent.setBackground(NuclosThemeSettings.BACKGROUND_INACTIVECOLUMN);
                        }
                    }
                }
                //               }

                try {
                    EntityMetaDataVO meta = MetaDataClientProvider.getInstance()
                            .getEntity(clctef.getEntityName());
                    if (meta.getRowColorScript() != null && !bSelected) {
                        AbstractCollectableComponent.setBackground(cellRendererComponent,
                                meta.getRowColorScript(), clct, meta, isEnabled);
                    }
                } catch (CommonFatalException ex) {
                    LOG.warn(ex);
                }
            }
        }
    }

    if (tbl instanceof TableRowMouseOverSupport) {
        TableRowMouseOverSupport trmos = (TableRowMouseOverSupport) tbl;
        if (trmos.isMouseOverRow(iRow)) {
            final Color bgColor = LangUtils.defaultIfNull(cellRendererComponent.getBackground(), Color.WHITE);
            cellRendererComponent
                    .setBackground(new Color(Math.max(0, bgColor.getRed() - (bgColor.getRed() * 8 / 100)),
                            Math.max(0, bgColor.getGreen() - (bgColor.getGreen() * 8 / 100)),
                            Math.max(0, bgColor.getBlue() - (bgColor.getBlue() * 8 / 100))));
            //            cellRendererComponent.setBackground(UIManager.getColor("Table.selectionBackground"));
        }
    }
}

From source file:org.nuclos.client.ui.collect.result.ResultController.java

/**
 * command: select columns//from  w  w  w.  j  av a2s.c o m
 * Lets the user select the columns to show in the result list.
 */
public void cmdSelectColumns(final ChoiceEntityFieldList fields) {
    final SelectColumnsController ctl = new SelectColumnsController(clctctl.getTab());
    // final List<CollectableEntityField> lstAvailable = (List<CollectableEntityField>) fields.getAvailableFields();
    // final List<CollectableEntityField> lstSelected = (List<CollectableEntityField>) fields.getSelectedFields();
    final ResultPanel<Clct> panel = getResultPanel();
    final JTable tbl = panel.getResultTable();

    final Map<String, Integer> mpWidths = panel.getVisibleColumnWidth(fields.getSelectedFields());
    ctl.setModel(fields);
    final boolean bOK = ctl.run(getSpringLocaleDelegate().getMessage("SelectColumnsController.1",
            "Anzuzeigende Spalten ausw\u00e4hlen"));

    if (bOK) {
        UIUtils.runCommand(clctctl.getTab(), new CommonRunnable() {
            @Override
            public void run() throws CommonBusinessException {
                final int iSelectedRow = tbl.getSelectedRow();
                fields.set(ctl.getAvailableObjects(), ctl.getSelectedObjects(),
                        clctctl.getResultController().getCollectableEntityFieldComparator());
                final List<? extends CollectableEntityField> lstSelectedNew = fields.getSelectedFields();
                ((CollectableTableModel<?>) tbl.getModel()).setColumns(lstSelectedNew);
                panel.setupTableCellRenderers(tbl);
                Collection<CollectableEntityField> collNewlySelected = new ArrayList<CollectableEntityField>(
                        lstSelectedNew);
                collNewlySelected.removeAll(fields.getSelectedFields());
                if (!collNewlySelected.isEmpty()) {
                    if (!clctctl.getSearchStrategy().getCollectablesInResultAreAlwaysComplete()) {
                        // refresh the result:
                        clctctl.getResultController().getSearchResultStrategy().refreshResult();
                    }
                }

                // reselect the previously selected row (which gets lost be refreshing the model)
                if (iSelectedRow != -1) {
                    tbl.setRowSelectionInterval(iSelectedRow, iSelectedRow);
                }

                isIgnorePreferencesUpdate = true;
                panel.restoreColumnWidths(ctl.getSelectedObjects(), mpWidths);
                isIgnorePreferencesUpdate = false;

                // Set the newly added columns to optimal width
                for (CollectableEntityField clctef : collNewlySelected) {
                    TableUtils.setOptimalColumnWidth(tbl,
                            tbl.getColumnModel().getColumnIndex(clctef.getLabel()));
                }
            }
        });
    }
}

From source file:org.nuclos.client.ui.collect.SubForm.java

private CollectableComponentType getTypeFromClassField(SubFormTableModel tableModel, String fieldname,
        int rowIndex) {
    int typeId = CollectableComponentTypes.TYPE_TEXTFIELD;

    JTable table = getJTable();
    Object oValue = table.getModel().getValueAt(rowIndex, tableModel.findColumnByFieldName(fieldname));

    try {/*from  w w w  .j a  v  a 2s. c  o m*/
        typeId = CollectableUtils.getCollectableComponentTypeForClass(Class.forName(oValue.toString()));
    } catch (ClassNotFoundException e) {
        throw new CommonFatalException(e);
    }

    return new CollectableComponentType(typeId, null);
}

From source file:org.nuclos.client.ui.collect.SubForm.java

private Class<?> getClassFromFieldname(SubFormTableModel tableModel, String fieldName, int rowIndex)
        throws ClassNotFoundException {
    JTable table = getJTable();
    Object oValue = table.getModel().getValueAt(rowIndex, tableModel.findColumnByFieldName(fieldName));

    return Class.forName(oValue.toString());
}

From source file:org.openconcerto.erp.core.finance.accounting.ui.AjouterComptePCGtoPCEFrame.java

private void ajoutCompteSelected() {

    SQLTable compteTable = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete()
            .getTable("COMPTE_PCE");

    JTable tabTmp = (JTable) (this.planPanel.getTables().get(this.planPanel.getSelectedIndex()));
    PlanComptableGModel modelTmp = (PlanComptableGModel) tabTmp.getModel();

    int[] selectRows = tabTmp.getSelectedRows();

    if (selectRows.length == 0) {
        return;//from   www.  ja  va  2s. com
    }

    // On verifie que les compte n'existent pas deja
    SQLSelect selCompte = new SQLSelect(compteTable.getBase());
    selCompte.addSelect(compteTable.getField("NUMERO"));

    Where w = new Where(compteTable.getField("NUMERO"), "=", tabTmp.getValueAt(selectRows[0], 0));

    for (int i = 1; i < selectRows.length; i++) {
        w.or(new Where(compteTable.getField("NUMERO"), "=", tabTmp.getValueAt(selectRows[i], 0)));
    }

    String reqCompte = selCompte.asString();
    Object obRep = ((ComptaPropsConfiguration) Configuration.getInstance()).getSQLBaseSociete().getDataSource()
            .execute(reqCompte, new ArrayListHandler());

    List tmpCpt = (List) obRep;

    // Map qui contient les comptes existants
    Map<String, Integer> mCompte;
    if (tmpCpt.size() == 0) {
        mCompte = null;
    } else {
        mCompte = new HashMap<String, Integer>();
        for (int i = 0; i < tmpCpt.size(); i++) {
            Object[] tmp = (Object[]) tmpCpt.get(i);
            mCompte.put(tmp[0].toString().trim(), new Integer(0));
        }
    }

    // on ajoute les comptes si ils n'existent pas
    for (int i = 0; i < selectRows.length; i++) {
        if ((mCompte != null) && (mCompte.get(tabTmp.getValueAt(selectRows[i], 0).toString().trim()) == null)) {

            System.out.println("Ajout du compte" + tabTmp.getValueAt(selectRows[i], 0) + "  "
                    + tabTmp.getValueAt(selectRows[i], 1));
            SQLRowValues val = new SQLRowValues(compteTable);
            val.put("NUMERO", tabTmp.getValueAt(selectRows[i], 0));
            val.put("NOM", tabTmp.getValueAt(selectRows[i], 1));
            val.put("INFOS", ((Compte) modelTmp.getComptes().get(selectRows[i])).getInfos());

            try {
                val.insert();
            } catch (SQLException sqlE) {
                System.err.println("Error insert row in table COMPTE_PCE");
                sqlE.printStackTrace();
            }
        }
    }
}

From source file:org.openconcerto.erp.core.finance.accounting.ui.GrandLivrePanel.java

/**
 * Cree un JTable contenant les ecritures du compte pass en argument
 * //from w ww.  ja  v a2s.  co  m
 * @param compte
 * @return null si aucune ecriture
 */
private JTable createJTableCompte(Compte compte) {

    // on cree la JTable
    final JTable tableTmp = creerJTable(compte);

    if (tableTmp != null) {

        // On met en place le renderer
        EcritureGrandLivreRenderer ecritureRenderer = new EcritureGrandLivreRenderer(
                ((TableSorter) tableTmp.getModel()));

        for (int j = 0; j < tableTmp.getColumnCount(); j++) {
            tableTmp.getColumnModel().getColumn(j).setCellRenderer(ecritureRenderer);
        }

        // Gestion de la souris sur la JTable
        tableTmp.addMouseListener(new MouseAdapter() {

            public void mousePressed(final MouseEvent mE) {

                if (mE.getButton() == MouseEvent.BUTTON3) {
                    JPopupMenu menuDroit = new JPopupMenu();

                    menuDroit.add(new AbstractAction("Voir la source") {

                        public void actionPerformed(ActionEvent e) {
                            int row = tableTmp.rowAtPoint(mE.getPoint());

                            TableSorter s = (TableSorter) tableTmp.getModel();

                            int modelIndex = s.modelIndex(row);
                            ConsultCompteModel consultCompteModel = ((ConsultCompteModel) s.getTableModel());
                            Ecriture ecriture = consultCompteModel.getEcritures().get(modelIndex);

                            MouvementSQLElement.showSource(ecriture.getIdMvt());

                        }
                    });
                    menuDroit.show(mE.getComponent(), mE.getX(), mE.getY());
                }
            }
        });

    }
    return tableTmp;
}

From source file:org.openmicroscopy.shoola.agents.measurement.util.ui.ResultsCellRenderer.java

/**
 * @see TableCellRenderer#getTableCellRendererComponent(JTable, Object, 
 *                               boolean, boolean, int, int)
 *//*from   w  ww  .jav  a  2 s .  c  o  m*/
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column) {
    Component thisComponent = new JLabel();
    JLabel label = new JLabel();
    label.setOpaque(true);

    if (value instanceof Number) {
        MeasurementTableModel tm = (MeasurementTableModel) table.getModel();
        KeyDescription key = tm.getColumnNames().get(column);
        String k = key.getKey();
        MeasurementUnits units = tm.getUnitsType();
        Number n = (Number) value;
        String s;
        if (units.isInMicrons()) {
            UnitsObject object;
            StringBuffer buffer = new StringBuffer();
            object = UIUtilities.transformSize(n.doubleValue());
            s = twoDecimalPlaces(object.getValue());
            if (StringUtils.isNotBlank(s)) {
                buffer.append(s);
                if (!(AnnotationKeys.ANGLE.getKey().equals(k) || AnnotationDescription.ZSECTION_STRING.equals(k)
                        || AnnotationDescription.ROIID_STRING.equals(k)
                        || AnnotationDescription.TIME_STRING.equals(k))) {
                    buffer.append(object.getUnits());
                }
                if (AnnotationKeys.AREA.getKey().equals(k)) {
                    buffer = new StringBuffer();
                    object = UIUtilities.transformSquareSize(n.doubleValue());
                    s = twoDecimalPlaces(object.getValue());
                    buffer.append(s);
                    buffer.append(object.getUnits());
                }
                label.setText(buffer.toString());
            }
        } else {
            s = UIUtilities.twoDecimalPlaces(n.doubleValue());
            if (StringUtils.isNotBlank(s)) {
                label.setText(s);
            }
        }
        thisComponent = label;
    } else if (value instanceof FigureType || value instanceof String) {
        thisComponent = makeShapeIcon(label, "" + value);
    } else if (value instanceof Color) {
        label.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY));
        label.setBackground((Color) value);
        thisComponent = label;
    } else if (value instanceof Boolean) {
        JCheckBox checkBox = new JCheckBox();
        checkBox.setSelected((Boolean) value);
        thisComponent = checkBox;
    } else if (value instanceof ArrayList) {
        thisComponent = createList(value);
        //return list;
    }
    if (!(value instanceof Color)) {
        RendererUtils.setRowColor(thisComponent, table.getSelectedRow(), row);
        if (label != null)
            label.setBackground(thisComponent.getBackground());
    }
    return thisComponent;
}

From source file:org.pentaho.reporting.designer.extensions.pentaho.repository.util.RepositoryEntryCellRenderer.java

public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected,
        final boolean hasFocus, final int row, final int column) {
    final JLabel component = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
            row, column);//from   w w w  .  ja va  2 s .co m
    try {
        if (column == 0) {
            final RepositoryTableModel tableModel = (RepositoryTableModel) table.getModel();
            final RowSorter rowSorter = table.getRowSorter();
            final FileObject e;
            if (rowSorter != null) {
                e = tableModel.getElementForRow(rowSorter.convertRowIndexToModel(row));
            } else {
                e = tableModel.getElementForRow(row);
            }

            if (e.getType() == FileType.FOLDER) {
                component.setIcon(closedIcon);
            } else {
                component.setIcon(leafIcon);
            }
        } else {
            component.setIcon(null);
        }
    } catch (FileSystemException fse) {
        // ok, ugly, but not fatal.
    }
    return component;
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public TransferHandler dragRows(final JTable table, final List<String> specs) {
    TransferHandler th = null;//w  w w. j ava2s  .c  o m
    try {
        final DataFlavor ndf = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType);
        final DataFlavor df = DataFlavor.getTextPlainUnicodeFlavor();
        final String charset = df.getParameter("charset");
        final Transferable transferable = new Transferable() {
            @Override
            public Object getTransferData(DataFlavor arg0) throws UnsupportedFlavorException, IOException {
                if (arg0.equals(ndf)) {
                    int[] rr = currentRowSelection; //table.getSelectedRows();
                    List<String> selseq = new ArrayList<String>(rr.length);
                    for (int r : rr) {
                        int i = table.convertRowIndexToModel(r);
                        selseq.add(specs.get(i));
                    }
                    return selseq;
                } else {
                    String ret = "";//makeCopyString();
                    for (int r = 0; r < table.getRowCount(); r++) {
                        Object o = table.getValueAt(r, 0);
                        if (o != null) {
                            ret += o.toString();
                        } else {
                            ret += "";
                        }
                        for (int c = 1; c < table.getColumnCount(); c++) {
                            o = table.getValueAt(r, c);
                            if (o != null) {
                                ret += "\t" + o.toString();
                            } else {
                                ret += "\t";
                            }
                        }
                        ret += "\n";
                    }
                    //return arg0.getReaderForText( this );
                    return new ByteArrayInputStream(ret.getBytes(charset));
                }
                //return ret;
            }

            @Override
            public DataFlavor[] getTransferDataFlavors() {
                return new DataFlavor[] { df, ndf };
            }

            @Override
            public boolean isDataFlavorSupported(DataFlavor arg0) {
                if (arg0.equals(df) || arg0.equals(ndf)) {
                    return true;
                }
                return false;
            }
        };

        th = new TransferHandler() {
            private static final long serialVersionUID = 1L;

            public int getSourceActions(JComponent c) {
                return TransferHandler.COPY_OR_MOVE;
            }

            public boolean canImport(TransferHandler.TransferSupport support) {
                return true;
            }

            protected Transferable createTransferable(JComponent c) {
                currentRowSelection = table.getSelectedRows();

                return transferable;
            }

            public boolean importData(TransferHandler.TransferSupport support) {
                try {
                    System.err.println(table.getSelectedRows().length);

                    DataFlavor[] dfs = support.getDataFlavors();
                    if (support.isDataFlavorSupported(ndf)) {
                        Object obj = support.getTransferable().getTransferData(ndf);
                        ArrayList<String> seqs = (ArrayList<String>) obj;

                        /*ArrayList<String> newlist = new ArrayList<String>( serifier.lgse.size() );
                        for( int r = 0; r < table.getRowCount(); r++ ) {
                           int i = table.convertRowIndexToModel(r);
                           newlist.add( specs.get(i) );
                        }
                        serifier.lgseq.clear();
                        serifier.lgseq = newlist;*/

                        Point p = support.getDropLocation().getDropPoint();
                        int k = table.rowAtPoint(p);

                        specs.removeAll(seqs);
                        for (String s : seqs) {
                            specs.add(k++, s);
                        }

                        TableRowSorter<TableModel> trs = (TableRowSorter<TableModel>) table.getRowSorter();
                        trs.setSortKeys(null);

                        table.tableChanged(new TableModelEvent(table.getModel()));

                        return true;
                    } /* else if( support.isDataFlavorSupported( df ) ) {                     
                        Object obj = support.getTransferable().getTransferData( df );
                        InputStream is = (InputStream)obj;
                                
                        System.err.println( charset );
                        importReader( new BufferedReader(new InputStreamReader(is, charset)) );
                                
                        updateView();
                                
                        return true;
                      }  else if( support.isDataFlavorSupported( DataFlavor.stringFlavor ) ) {                     
                        Object obj = support.getTransferable().getTransferData( DataFlavor.stringFlavor );
                        String str = (String)obj;
                        importReader( new BufferedReader( new StringReader(str) ) );
                                
                        updateView();
                                
                        return true;
                      }*/
                } catch (UnsupportedFlavorException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return false;
            }
        };
    } catch (Exception e) {
        e.printStackTrace();
    }
    return th;
}

From source file:org.simmi.GeneSetHead.java

License:asdf

public void updateFilter(int val, String ustr, JTable table, RowFilter filter, Set<Integer> filterset,
        Label label, int... ind) {
    filterset.clear();/*from   www .j  a  va 2 s . c  o m*/
    TableModel model = table.getModel();
    for (int r = 0; r < model.getRowCount(); r++) {
        for (int i = 0; i < ind.length; i++) {
            String vstr = (String) model.getValueAt(r, ind[i]);
            String s = vstr != null ? vstr.toLowerCase() : null;

            if ((s != null && s.contains(ustr))) {
                filterset.add(r);
                break;
            }
        }
    }

    if (filterset.isEmpty()) {
        int i = 0;
        if (table.getModel() == groupModel) {
            for (GeneGroup gg : geneset.allgenegroups) {
                for (Gene g : gg.genes) {
                    if (g.refid.toLowerCase().contains(ustr)) {
                        filterset.add(i);
                        break;
                    }
                }
                i++;
            }
        } else {
            for (Gene g : geneset.genelist) {
                if (g.refid.toLowerCase().contains(ustr)) {
                    filterset.add(i);
                }
                i++;
            }
        }
    }

    updateFilter(table, filter, label);
}