Example usage for javax.swing.table TableCellRenderer TableCellRenderer

List of usage examples for javax.swing.table TableCellRenderer TableCellRenderer

Introduction

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

Prototype

TableCellRenderer

Source Link

Usage

From source file:Main.java

private TableCellRenderer getCellRenderer() {
    return new TableCellRenderer() {
        JComboBox<String> box = new JComboBox<>(new String[] { "1", "2" });

        @Override//w  ww . j  a va  2  s.  co  m
        public Component getTableCellRendererComponent(JTable arg0, Object arg1, boolean arg2, boolean arg3,
                int arg4, int arg5) {
            box.setSelectedItem(arg1);
            return box;
        }
    };
}

From source file:au.com.jwatmuff.eventmanager.util.GUIUtils.java

public static void leftAlignTable(JTable table) {
    Enumeration<TableColumn> cols = table.getColumnModel().getColumns();
    while (cols.hasMoreElements()) {
        TableColumn col = cols.nextElement();
        final TableCellRenderer oldRenderer = col.getCellRenderer();
        if (oldRenderer == null) {
            col.setCellRenderer(new DefaultTableCellRenderer() {
                @Override/*from  w w  w.j  a va  2s . com*/
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                    Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                            column);
                    if (c instanceof JLabel) {
                        ((JLabel) c).setHorizontalAlignment(SwingConstants.LEFT);
                    }
                    return c;
                }
            });
        } else {
            col.setCellRenderer(new TableCellRenderer() {
                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                    Component c = oldRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus,
                            row, column);
                    if (c instanceof JLabel) {
                        ((JLabel) c).setHorizontalAlignment(SwingConstants.LEFT);
                    }
                    return c;
                }
            });
        }
    }
}

From source file:es.emergya.ui.plugins.AdminPanel.java

/**
 * /*  www  .java 2 s .  co  m*/
 * @param columnNames
 *            nombres de las columnas de la tabla
 * @param filterOptions
 *            lista de opciones de un combobox. Si esta vacio entonces es un
 *            textfield
 * @param noFiltrarAction
 * @param filtrarAction
 */
public void generateTable(String[] columnNames, Object[][] filterOptions,
        AdminPanel.NoFiltrarAction noFiltrarAction, AdminPanel.FiltrarAction filtrarAction) {

    if (columnNames == null) {
        columnNames = new String[] {};
    }
    if (filterOptions == null) {
        filterOptions = new Object[][] {};
    }

    String filterString = "[";
    for (Object[] o : filterOptions) {
        filterString += Arrays.toString(o) + " ";
    }
    filterString += "]";

    log.debug("generateTable( columnNames = " + Arrays.toString(columnNames) + ", filterOptions = "
            + filterString + ")");

    tablePanel.removeAll();
    int columnNamesLength = columnNames.length;
    if (!getCanDelete())
        columnNamesLength++;
    MyTableModel dataModel = new MyTableModel(1, columnNamesLength + 2) {

        private static final long serialVersionUID = 1348355328684460769L;

        @Override
        public boolean isCellEditable(int row, int column) {
            return column != 0 && !invisibleFilterCols.contains(column);
        }
    };
    filters = new JTable(dataModel) {

        private static final long serialVersionUID = -8266991359840905405L;

        @Override
        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);

            if (isCellEditable(row, column) && column != getColumnCount() - 1) {
                if (c instanceof JTextField) {
                    ((JTextField) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
                } else if (c instanceof JComboBox) {
                    ((JComboBox) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
                } else if (c instanceof JLabel) {
                    ((JLabel) c).setBorder(new MatteBorder(1, 1, 1, 1, Color.BLACK));
                }
            }
            return c;
        }
    };
    filters.setSurrendersFocusOnKeystroke(true);
    filters.setShowGrid(false);
    filters.setRowHeight(22);
    filters.setOpaque(false);

    for (Integer i = 0; i < filterOptions.length; i++) {
        final Object[] items = filterOptions[i];
        if (items != null && items.length > 1) {
            setComboBoxEditor(i, items);
        } else {
            final DefaultCellEditor defaultCellEditor = new DefaultCellEditor(new JTextField());
            defaultCellEditor.setClickCountToStart(1);
            filters.getColumnModel().getColumn(i + 1).setCellEditor(defaultCellEditor);
        }
    }

    filters.setRowSelectionAllowed(false);
    filters.setDragEnabled(false);
    filters.setColumnSelectionAllowed(false);
    filters.setDefaultEditor(JButton.class, new JButtonCellEditor());

    filters.setDefaultRenderer(Object.class, new DefaultTableRenderer() {
        private static final long serialVersionUID = -4811729559786534118L;

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

    });

    filters.setDefaultRenderer(JButton.class, new TableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JButton b = (JButton) value;
            b.setBorderPainted(false);
            b.setContentAreaFilled(false);
            return b;
        }
    });
    filters.setDefaultRenderer(JLabel.class, new TableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            return (JLabel) value;
        }
    });
    filters.setDefaultEditor(JButton.class, new JButtonCellEditor());
    filters.getModel().setValueAt(new JLabel(""), 0, 0);
    JButton jButton2 = new JButton(noFiltrarAction);
    JButton jButton = new JButton(filtrarAction);
    jButton.setBorderPainted(false);
    jButton2.setBorderPainted(false);
    jButton.setContentAreaFilled(false);
    jButton2.setContentAreaFilled(false);
    if (jButton.getIcon() != null)
        jButton.setPreferredSize(
                new Dimension(jButton.getIcon().getIconWidth(), jButton.getIcon().getIconHeight()));
    if (jButton2.getIcon() != null)
        jButton2.setPreferredSize(
                new Dimension(jButton2.getIcon().getIconWidth(), jButton2.getIcon().getIconHeight()));

    filters.getModel().setValueAt(jButton, 0, columnNamesLength - 1);
    filters.getColumnModel().getColumn(columnNamesLength - 1).setMinWidth(jButton.getWidth() + 24);
    filters.getModel().setValueAt(jButton2, 0, columnNamesLength);
    filters.getColumnModel().getColumn(columnNamesLength).setMinWidth(jButton2.getWidth() + 14);
    cuenta.setHorizontalAlignment(JLabel.CENTER);
    cuenta.setText("?/?");
    filters.getModel().setValueAt(cuenta, 0, columnNamesLength + 1);

    tablePanel.add(filters, BorderLayout.NORTH);

    Vector<String> headers = new Vector<String>();
    headers.add("");
    headers.addAll(Arrays.asList(columnNames));
    MyTableModel model = new MyTableModel(headers, 0);
    table = new JTable(model) {

        private static final long serialVersionUID = 949284378605881770L;
        private int highLightedRow = -1;
        private Rectangle dirtyRegion = null;

        public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
            Component c = super.prepareRenderer(renderer, row, column);
            try {
                if (AdminPanel.this.myRendererColoring != null)
                    c.setBackground(AdminPanel.this.myRendererColoring
                            .getColor(AdminPanel.this.table.getValueAt(row, 1)));
            } catch (Throwable t) {
                log.error("Error al colorear la celda: " + t);
            }
            return c;
        }

        @Override
        protected void processMouseMotionEvent(MouseEvent e) {
            try {
                int row = rowAtPoint(e.getPoint());
                Graphics g = getGraphics();
                if (row == -1) {
                    highLightedRow = -1;
                }

                // row changed
                if (highLightedRow != row) {
                    if (null != dirtyRegion) {
                        paintImmediately(dirtyRegion);
                    }
                    for (int j = 0; j < getRowCount(); j++) {
                        if (row == j) {
                            // highlight
                            Rectangle firstRowRect = getCellRect(row, 0, false);
                            Rectangle lastRowRect = getCellRect(row, getColumnCount() - 1, false);
                            dirtyRegion = firstRowRect.union(lastRowRect);
                            g.setColor(new Color(0xff, 0xff, 0, 100));
                            g.fillRect((int) dirtyRegion.getX(), (int) dirtyRegion.getY(),
                                    (int) dirtyRegion.getWidth(), (int) dirtyRegion.getHeight());
                            highLightedRow = row;
                        }

                    }
                }
            } catch (Exception ex) {
            }
            super.processMouseMotionEvent(e);
        }
    };

    table.setRowHeight(22);

    table.setOpaque(false);
    // table.setAutoCreateRowSorter(true);

    table.setDragEnabled(false);
    table.getTableHeader().setReorderingAllowed(false);
    table.getTableHeader().setResizingAllowed(false);

    table.setDefaultEditor(JButton.class, new JButtonCellEditor());
    table.setDefaultRenderer(JButton.class, new TableCellRenderer() {

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JButton b = (JButton) value;
            if (b != null) {
                b.setBorderPainted(false);
                b.setContentAreaFilled(false);
            }
            return b;
        }
    });

    JScrollPane jScrollPane = new JScrollPane(table);
    jScrollPane.setOpaque(false);
    jScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    jScrollPane.getViewport().setOpaque(false);
    tablePanel.add(jScrollPane, BorderLayout.CENTER);
}

From source file:de.codesourcery.eve.skills.ui.components.impl.AssetListComponent.java

@Override
protected JPanel createPanel() {

    // Merge controls.
    final JPanel mergeControlsPanel = new JPanel();
    mergeControlsPanel.setLayout(new GridBagLayout());
    mergeControlsPanel.setBorder(BorderFactory.createTitledBorder("Merging"));

    int y = 0;/*from ww  w  .jav  a 2  s  . c  o m*/

    // merge by type
    mergeAssetsByType.setSelected(true);
    mergeAssetsByType.addActionListener(actionListener);

    mergeControlsPanel.add(mergeAssetsByType, constraints(0, y).anchorWest().end());
    mergeControlsPanel.add(new JLabel("Merge assets by type", SwingConstants.LEFT),
            constraints(1, y++).width(2).end());

    // "ignore different packaging"
    ignorePackaging.setSelected(true);
    ignorePackaging.addActionListener(actionListener);

    mergeControlsPanel.add(new JLabel(""), constraints(0, y).anchorWest().end());
    mergeControlsPanel.add(ignorePackaging, constraints(1, y).anchorWest().end());
    final JLabel label1 = new JLabel("Merge different packaging", SwingConstants.RIGHT);
    mergeControlsPanel.add(label1, constraints(2, y++).end());

    // "ignore different locations"
    ignoreLocations.setSelected(true);
    ignoreLocations.addActionListener(actionListener);

    mergeControlsPanel.add(new JLabel(""), constraints(0, y).anchorWest().end());
    mergeControlsPanel.add(ignoreLocations, constraints(1, y).anchorWest().end());
    final JLabel label2 = new JLabel("Merge different locations", SwingConstants.RIGHT);
    mergeControlsPanel.add(label2, constraints(2, y++).end());

    linkComponentEnabledStates(mergeAssetsByType, ignoreLocations, ignorePackaging, label1, label2);

    /*
     * Filter controls.
     */

    final JPanel filterControlsPanel = new JPanel();
    filterControlsPanel.setLayout(new GridBagLayout());
    filterControlsPanel.setBorder(BorderFactory.createTitledBorder("Filters"));

    y = 0;
    // filter by location combo box
    filterByLocation.addActionListener(actionListener);
    locationComboBox.addActionListener(actionListener);

    filterByLocation.setSelected(false);
    linkComponentEnabledStates(filterByLocation, locationComboBox);

    locationComboBox.setRenderer(new LocationRenderer());
    locationComboBox.setPreferredSize(new Dimension(150, 20));
    locationComboBox.setModel(locationModel);

    filterControlsPanel.add(filterByLocation, constraints(0, y).end());
    filterControlsPanel.add(locationComboBox, constraints(1, y++).end());

    // filter by type combo box
    filterByType.addActionListener(actionListener);
    typeComboBox.addActionListener(actionListener);

    filterByType.setSelected(false);

    linkComponentEnabledStates(filterByType, typeComboBox);

    typeComboBox.setPreferredSize(new Dimension(150, 20));
    typeComboBox.setModel(typeModel);

    filterControlsPanel.add(filterByType, constraints(0, y).end());
    filterControlsPanel.add(typeComboBox, constraints(1, y++).end());

    // filter by item category combobox
    filterByCategory.addActionListener(actionListener);
    categoryComboBox.addActionListener(actionListener);
    categoryComboBox.setRenderer(new DefaultListCellRenderer() {

        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
                boolean cellHasFocus) {

            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

            setText(getDisplayName((InventoryCategory) value));
            setEnabled(categoryComboBox.isEnabled());
            return this;
        }
    });

    filterByCategory.setSelected(false);
    linkComponentEnabledStates(filterByCategory, categoryComboBox);

    categoryComboBox.setPreferredSize(new Dimension(150, 20));
    categoryComboBox.setModel(categoryModel);

    filterControlsPanel.add(filterByCategory, constraints(0, y).end());
    filterControlsPanel.add(categoryComboBox, constraints(1, y++).end());

    // filter by item group combobox
    filterByGroup.addActionListener(actionListener);
    groupComboBox.addActionListener(actionListener);

    filterByGroup.setSelected(false);

    linkComponentEnabledStates(filterByGroup, groupComboBox);

    groupComboBox.setPreferredSize(new Dimension(150, 20));
    groupComboBox.setModel(groupModel);

    filterControlsPanel.add(filterByGroup, constraints(0, y).end());
    filterControlsPanel.add(groupComboBox, constraints(1, y++).end());

    /*
     * Table panel.
     */

    table = new JTable() {

        @Override
        public TableCellRenderer getCellRenderer(int row, int column) {

            // subclassing hack is needed because table
            // returns different renderes depending on column type
            final TableCellRenderer result = super.getCellRenderer(row, column);

            return new TableCellRenderer() {

                @Override
                public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {

                    final Component comp = result.getTableCellRendererComponent(table, value, isSelected,
                            hasFocus, row, column);

                    final int modelRow = table.convertRowIndexToModel(row);
                    final Asset asset = model.getRow(modelRow);

                    final StringBuilder label = new StringBuilder("<HTML><BODY>");
                    label.append(asset.getItemId() + " - flags: " + asset.getFlags() + "<BR>");
                    if (asset.hasMultipleLocations()) {
                        label.append("<BR>");
                        for (ILocation loc : asset.getLocations()) {
                            label.append(loc.getDisplayName()).append("<BR>");
                        }
                    }

                    label.append("</BODY></HTML>");
                    ((JComponent) comp).setToolTipText(label.toString());

                    return comp;
                }
            };
        }
    };

    model.setViewFilter(this.viewFilter);

    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            updateSelectedVolume();
        }
    });

    FixedBooleanTableCellRenderer.attach(table);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setModel(model);
    table.setBorder(BorderFactory.createLineBorder(Color.BLACK));
    table.setRowSorter(model.getRowSorter());

    popupMenuBuilder.addItem("Refine...", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final List<Asset> assets = getSelectedAssets();
            if (assets == null || assets.isEmpty()) {
                return;
            }

            final ICharacter c = selectionProvider.getSelectedItem();
            final RefiningComponent comp = new RefiningComponent(c);
            comp.setItemsToRefine(assets);
            ComponentWrapper.wrapComponent("Refining", comp).setVisible(true);
        }

        @Override
        public boolean isEnabled() {
            return table.getSelectedRow() != -1;
        }
    });

    popupMenuBuilder.addItem("Copy selection to clipboard (text)", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final List<Asset> assets = getSelectedAssets();
            if (assets == null || assets.isEmpty()) {
                return;
            }

            new PlainTextTransferable(toPlainText(assets)).putOnClipboard();
        }

        @Override
        public boolean isEnabled() {
            return table.getSelectedRow() != -1;
        }
    });

    popupMenuBuilder.addItem("Copy selection to clipboard (CSV)", new AbstractAction() {

        @Override
        public void actionPerformed(ActionEvent e) {
            final List<Asset> assets = getSelectedAssets();
            if (assets == null || assets.isEmpty()) {
                return;
            }

            final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

            clipboard.setContents(new PlainTextTransferable(toCsv(assets)), null);
        }

        @Override
        public boolean isEnabled() {
            return table.getSelectedRow() != -1;
        }
    });

    table.getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    this.popupMenuBuilder.attach(table);

    final JScrollPane scrollPane = new JScrollPane(table);

    /*
     * Name filter
     */

    final JPanel nameFilterPanel = new JPanel();
    nameFilterPanel.setLayout(new GridBagLayout());
    nameFilterPanel.setBorder(BorderFactory.createTitledBorder("Filter by name"));
    nameFilterPanel.setPreferredSize(new Dimension(150, 70));
    nameFilter.setColumns(10);
    nameFilter.getDocument().addDocumentListener(new DocumentListener() {

        @Override
        public void changedUpdate(DocumentEvent e) {
            model.viewFilterChanged();
        }

        @Override
        public void insertUpdate(DocumentEvent e) {
            model.viewFilterChanged();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            model.viewFilterChanged();
        }
    });

    nameFilterPanel.add(nameFilter, constraints(0, 0).resizeHorizontally().end());
    final JButton clearButton = new JButton("Clear");
    clearButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            nameFilter.setText(null);
        }
    });
    nameFilterPanel.add(clearButton, constraints(1, 0).noResizing().end());

    // Selected volume
    final JPanel selectedVolumePanel = this.selectedVolume.getPanel();

    // add control panels to result panel
    final JPanel topPanel = new JPanel();
    topPanel.setLayout(new GridBagLayout());

    topPanel.add(mergeControlsPanel, constraints(0, 0).height(2).weightX(0).anchorWest().end());
    topPanel.add(filterControlsPanel, constraints(1, 0).height(2).anchorWest().weightX(0).end());
    topPanel.add(nameFilterPanel, constraints(2, 0).height(1).anchorWest().useRemainingWidth().end());
    topPanel.add(selectedVolumePanel, constraints(2, 1).height(1).anchorWest().useRemainingWidth().end());

    final JSplitPane splitPane = new ImprovedSplitPane(JSplitPane.VERTICAL_SPLIT, topPanel, scrollPane);

    splitPane.setDividerLocation(0.3d);

    final JPanel content = new JPanel();
    content.setLayout(new GridBagLayout());
    content.add(splitPane, constraints().resizeBoth().useRemainingSpace().end());

    return content;
}

From source file:org.apache.oodt.cas.workflow.gui.perspective.view.impl.DefaultPropView.java

private JTable createTable(final ViewState state) {
    JTable table;//from   ww w.j av a  2 s  . c o m
    final ModelGraph selected = state.getSelected();
    if (selected != null) {
        final Vector<Vector<String>> rows = new Vector<Vector<String>>();
        ConcurrentHashMap<String, String> keyToGroupMap = new ConcurrentHashMap<String, String>();
        Metadata staticMet = selected.getModel().getStaticMetadata();
        Metadata inheritedMet = selected.getInheritedStaticMetadata(state);
        Metadata completeMet = new Metadata();
        if (staticMet != null) {
            completeMet.replaceMetadata(staticMet.getSubMetadata(state.getCurrentMetGroup()));
        }
        if (selected.getModel().getExtendsConfig() != null) {
            for (String configGroup : selected.getModel().getExtendsConfig()) {
                Metadata extendsMetadata = state.getGlobalConfigGroups().get(configGroup).getMetadata()
                        .getSubMetadata(state.getCurrentMetGroup());
                for (String key : extendsMetadata.getAllKeys()) {
                    if (!completeMet.containsKey(key)) {
                        keyToGroupMap.put(key, configGroup);
                        completeMet.replaceMetadata(key, extendsMetadata.getAllMetadata(key));
                    }
                }
            }
        }
        if (inheritedMet != null) {
            Metadata inheritedMetadata = inheritedMet.getSubMetadata(state.getCurrentMetGroup());
            for (String key : inheritedMetadata.getAllKeys()) {
                if (!completeMet.containsKey(key)) {
                    keyToGroupMap.put(key, "__inherited__");
                    completeMet.replaceMetadata(key, inheritedMetadata.getAllMetadata(key));
                }
            }
        }
        List<String> keys = completeMet.getAllKeys();
        Collections.sort(keys);
        for (String key : keys) {
            if (key.endsWith("/envReplace")) {
                continue;
            }
            String values = StringUtils.join(completeMet.getAllMetadata(key), ",");
            Vector<String> row = new Vector<String>();
            row.add(keyToGroupMap.get(key));
            row.add(key);
            row.add(values);
            row.add(Boolean.toString(Boolean.parseBoolean(completeMet.getMetadata(key + "/envReplace"))));
            rows.add(row);
        }
        table = new JTable();// rows, new Vector<String>(Arrays.asList(new
                             // String[] { "key", "values", "envReplace" })));
        table.setModel(new AbstractTableModel() {
            public String getColumnName(int col) {
                switch (col) {
                case 0:
                    return "group";
                case 1:
                    return "key";
                case 2:
                    return "values";
                case 3:
                    return "envReplace";
                default:
                    return null;
                }
            }

            public int getRowCount() {
                return rows.size() + 1;
            }

            public int getColumnCount() {
                return 4;
            }

            public Object getValueAt(int row, int col) {
                if (row >= rows.size()) {
                    return null;
                }
                String value = rows.get(row).get(col);
                if (value == null && col == 3) {
                    return "false";
                }
                if (value == null && col == 0) {
                    return "__local__";
                }
                return value;
            }

            public boolean isCellEditable(int row, int col) {
                if (row >= rows.size()) {
                    return selected.getModel().getStaticMetadata().containsGroup(state.getCurrentMetGroup());
                }
                if (col == 0) {
                    return false;
                }
                String key = rows.get(row).get(1);
                return key == null || (selected.getModel().getStaticMetadata() != null
                        && selected.getModel().getStaticMetadata().containsKey(getKey(key, state)));
            }

            public void setValueAt(Object value, int row, int col) {
                if (row >= rows.size()) {
                    Vector<String> newRow = new Vector<String>(
                            Arrays.asList(new String[] { null, null, null, null }));
                    newRow.add(col, (String) value);
                    rows.add(newRow);
                } else {
                    Vector<String> rowValues = rows.get(row);
                    rowValues.add(col, (String) value);
                    rowValues.remove(col + 1);
                }
                this.fireTableCellUpdated(row, col);
            }

        });
        MyTableListener tableListener = new MyTableListener(state);
        table.getModel().addTableModelListener(tableListener);
        table.getSelectionModel().addListSelectionListener(tableListener);
    } else {
        table = new JTable(new Vector<Vector<String>>(),
                new Vector<String>(Arrays.asList(new String[] { "key", "values", "envReplace" })));
    }

    // table.setFillsViewportHeight(true);
    table.setSelectionBackground(Color.cyan);
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    TableCellRenderer cellRenderer = new TableCellRenderer() {

        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            JLabel field = new JLabel((String) value);
            if (column == 0) {
                field.setForeground(Color.gray);
            } else {
                if (isSelected) {
                    field.setBorder(new EtchedBorder(1));
                }
                if (table.isCellEditable(row, 1)) {
                    field.setForeground(Color.black);
                } else {
                    field.setForeground(Color.gray);
                }
            }
            return field;
        }

    };
    TableColumn groupCol = table.getColumnModel().getColumn(0);
    groupCol.setPreferredWidth(75);
    groupCol.setCellRenderer(cellRenderer);
    TableColumn keyCol = table.getColumnModel().getColumn(1);
    keyCol.setPreferredWidth(200);
    keyCol.setCellRenderer(cellRenderer);
    TableColumn valuesCol = table.getColumnModel().getColumn(2);
    valuesCol.setPreferredWidth(300);
    valuesCol.setCellRenderer(cellRenderer);
    TableColumn envReplaceCol = table.getColumnModel().getColumn(3);
    envReplaceCol.setPreferredWidth(75);
    envReplaceCol.setCellRenderer(cellRenderer);

    table.addMouseListener(new MouseListener() {
        public void mouseClicked(MouseEvent e) {
            if (e.getButton() == MouseEvent.BUTTON3 && DefaultPropView.this.table.getSelectedRow() != -1) {
                int row = DefaultPropView.this.table.getSelectedRow();// rowAtPoint(DefaultPropView.this.table.getMousePosition());
                String key = getKey((String) DefaultPropView.this.table.getValueAt(row, 1), state);
                Metadata staticMet = state.getSelected().getModel().getStaticMetadata();
                override.setVisible(staticMet == null || !staticMet.containsKey(key));
                delete.setVisible(staticMet != null && staticMet.containsKey(key));
                tableMenu.show(DefaultPropView.this.table, e.getX(), e.getY());
            }
        }

        public void mouseEntered(MouseEvent e) {
        }

        public void mouseExited(MouseEvent e) {
        }

        public void mousePressed(MouseEvent e) {
        }

        public void mouseReleased(MouseEvent e) {
        }
    });

    return table;
}

From source file:org.nuclos.client.genericobject.GenericObjectCollectController.java

/**
 * sets up a modified renderer for the result table header that uses the HTML formatted toString() value of the
 * column's entity field rather than its unformatted getLabel() value.
 *//*from  w w w . ja  va 2  s.  com*/
private void setupResultTableHeaderRenderer() {
    final JTableHeader header = getResultTable().getTableHeader();
    final TableCellRenderer headerrendererDefault = header.getDefaultRenderer();
    header.setDefaultRenderer(new TableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable tbl, Object oValue, boolean bSelected,
                boolean bHasFocus, int iRow, int iColumn) {
            final CollectableEntityField f = GenericObjectCollectController.this.getResultTableModel()
                    .getCollectableEntityField(tbl.convertColumnIndexToModel(iColumn));
            final String value;
            if (f instanceof CollectableEOEntityField) {
                // In the pivot case, we want to separate the column name
                // from the tool top.
                final CollectableEOEntityField field = (CollectableEOEntityField) f;
                final EntityFieldMetaDataVO ef = field.getMeta();
                if (ef.getPivotInfo() != null) {
                    value = ef.getField() + ":" + ef.getPivotInfo().getValueField();
                } else {
                    value = f.getLabel();
                }
            } else {
                value = f.getLabel();
            }
            return headerrendererDefault.getTableCellRendererComponent(tbl, value, bSelected, bHasFocus, iRow,
                    iColumn);
        }
    });
}

From source file:org.ut.biolab.medsavant.client.view.genetics.variantinfo.VariantFrequencyAggregatePane.java

public void setVariantRecords(Set<VariantRecord> records) {
    innerPanel.removeAll();//w  ww.java  2  s. c om
    //This function executes quickly, no need for waitPanel.
    //innerPanel.add(new WaitPanel("Loading DNA Ids..."));
    tableModel.setValues(records);
    aggregateTable = new AggregateTable(tableModel) {
        @Override
        //Necessary to enable buttons within the table.
        public boolean isCellEditable(int rowIndex, int colIndex) {
            return colIndex == buttonIndex;
        }

        //"Disables" selection within the aggregateTable.
        @Override
        public TableCellRenderer getCellRenderer(final int rowIndex, final int columnIndex) {
            final TableCellRenderer renderer = super.getCellRenderer(rowIndex, columnIndex);
            return new TableCellRenderer() {
                @Override
                public Component getTableCellRendererComponent(JTable jtable, final Object o, boolean bln,
                        boolean bln1, int i, int i1) {
                    return renderer.getTableCellRendererComponent(jtable, o, false, false, i, i1);
                }
            };
        }

        //This overridden method, together with the custom mouse listener on the 
        //AggregateTable header, disallows moving the first column, and columns
        //>= dnaIDIndex                    
        @Override
        protected AggregateTable.DraggingHandler createDraggingColumnPropertyChangeListener() {
            return new AggregateTable.DraggingHandler() {
                @Override
                public void columnMoved(TableColumnModelEvent e) {
                    if (fromColumnIndex == -1) {
                        fromColumnIndex = e.getFromIndex();
                    }
                    toColumnIndex = e.getToIndex();
                }

            };
        }
    };

    header = new AggregateTableHeader(aggregateTable);
    header.addMouseListener(new MouseAdapter() {
        //Disable moving the first column, or columns with index
        //>=dnaIDIndex
        @Override
        public void mouseReleased(MouseEvent e) {
            if (toColumnIndex != -1 && ((toColumnIndex == 0 || fromColumnIndex == 0)
                    || (toColumnIndex >= dnaIDIndex || fromColumnIndex >= dnaIDIndex))) {
                aggregateTable.moveColumn(toColumnIndex, fromColumnIndex);
                String msg = "This column cannot be moved.";
                DialogUtils.displayMessage(msg);
            } else {
                for (int columnHeaderIndex = 0; columnHeaderIndex < header.getColumnModel().getColumnCount()
                        - 2; columnHeaderIndex++) {
                    String columnTitle = (String) header.getColumnModel().getColumn(columnHeaderIndex)
                            .getHeaderValue();
                    aggregateColumns[columnHeaderIndex] = columnTitle;
                }
                reaggregate();
            }
            //aggregateTable.aggregate(this.aggregateColumns);
            fromColumnIndex = -1;
            toColumnIndex = -1;
            //expandAllButLast();
        }
    });

    header.setAutoFilterEnabled(false);
    header.setReorderingAllowed(true);
    header.setFont(TABLE_FONT_LARGE);
    aggregateTable.setTableHeader(header);
    aggregateTable.setAutoResizeMode(AggregateTable.AUTO_RESIZE_ALL_COLUMNS);
    aggregateTable.setFont(TABLE_FONT_LARGE);

    //Setup a custom "summary".  This is what calculates frequencies when cells are
    //collapsed
    PivotField f = aggregateTable.getAggregateTableModel().getField(BasicVariantColumns.DNA_ID.getAlias());
    f.setSummaryType(PivotConstants.SUMMARY_RESERVED_MAX + 1);
    aggregateTable.getAggregateTableModel().setSummaryCalculator(new SummaryCalculator() {
        private Set<String> collapsedDNAIDs = new HashSet<String>();
        private Values lastRowValues;
        private int valueCount = 0;
        private final int SUMMARY_FREQ = PivotConstants.SUMMARY_RESERVED_MAX + 1;

        @Override
        public void addValue(PivotValueProvider dataModel, PivotField field, Values rowValues,
                Values columnValues, Object object) {
            //this gets called multiple times for all the cells that disappear when 
            //something is collapsed.  
            // row[0] is the value of the corresponding first column: e.g. a Cohort or Family. 
            // columnValues can be ignored (blank)
            // Object is the value of the item in the cell that disappeared. (i.e. those cells which are being summarized)
            // field.getName() is the column name corresponding to Object

            // Useful Debugging code:                      
            //if(field.getName().equals(BasicVariantColumns.DNA_ID.getAlias())){

            /*
             System.out.println("==========");
             System.out.println("Field : " + field.getName());
             System.out.println("Row values: ");
                    
             for (int i = 0; i < rowValues.getCount(); ++i) {
             System.out.println("\trow[" + i + "] = " + rowValues.getValueAt(i).getValue());
                    
             }
                    
             System.out.println("Column values: ");
             for (int i = 0; i < columnValues.getCount(); ++i) {
             System.out.println("\tcol[" + i + "] = " + columnValues.getValueAt(i).getValue());
             }
                    
             System.out.println("Object: ");
             System.out.println("\t" + object);
             System.out.println("==========");
             */

            // }
            if (field.getName().equals(BasicVariantColumns.DNA_ID.getAlias())) {
                collapsedDNAIDs.add((String) object);
                lastRowValues = rowValues;
            } else {
                lastRowValues = null;
            }
            valueCount++;
        }

        //Should never be called
        @Override
        public void addValue(Object o) {
            LOG.error("Unexpected method invocation in OtherIndividualsSubInspector (1)");
        }

        //Should never be called
        @Override
        public void addValue(IPivotDataModel ipdm, PivotField pf, int i, int i1, Object o) {
            LOG.error("Unexpected method invocation in OtherIndividualsSubInspector (2)");
        }

        //Should never be called
        @Override
        public void addValue(PivotValueProvider pvp, PivotField pf, Object o) {
            LOG.error("Unexpected method invocation in OtherIndividualsSubInspector (3)");
        }

        @Override
        public void clear() {
            collapsedDNAIDs.clear();
            valueCount = 0;
            lastRowValues = null;
        }

        @Override
        public Object getSummaryResult(int type) {
            //if null, then we're not in the DNAId column.  Return null
            //to show a blank in this cell
            if (lastRowValues == null) {
                return null;
            }

            int numIndividuals = getNumberOfIndividualsInGroup(lastRowValues.getValueAt(0));

            return new Frequency(collapsedDNAIDs.size(), numIndividuals);
        }

        private int getNumberOfIndividualsInGroup(Value v) {
            if (aggregateColumns[0].equals("Cohort")) {
                //LOG.debug("Getting number of individuals in group " + v.getValue());
                Set<String> dnaIds = cohortDNAIDMap.get((Cohort) v.getValue());
                //for (String id : dnaIds) {
                //LOG.debug("\tGot id " + id);
                //}
                return cohortDNAIDMap.get((Cohort) v.getValue()).size();
            } else if (aggregateColumns[0].equals(BasicPatientColumns.FAMILY_ID.getAlias())) {
                return familyIDdnaIDMap.get((String) v.getValue()).size();
            } else {
                LOG.error("Invalid first column");
                return -1;
            }
        }

        @Override
        public long getCount() {
            return valueCount;
        }

        @Override
        public int getNumberOfSummaries() {
            return 1;
        }

        @Override
        public String getSummaryName(Locale locale, int i) {
            return "Frequency";
        }

        @Override
        public int[] getAllowedSummaries(Class<?> type) {
            return new int[] { SUMMARY_FREQ };
        }

        @Override
        public int[] getAllowedSummaries(Class<?> type, ConverterContext cc) {
            return new int[] { SUMMARY_FREQ };
        }
    });

    //Sets up the context menu for clicking column headers.  This will probably not be used
    //frequently.  Limit the available operations to collapsing, expanding, and grouping.
    TableHeaderPopupMenuInstaller installer = new TableHeaderPopupMenuInstaller(aggregateTable);
    installer.addTableHeaderPopupMenuCustomizer(new AggregateTablePopupMenuCustomizer() {
        @Override
        public void customizePopupMenu(JTableHeader header, JPopupMenu popup, int clickingColumn) {
            super.customizePopupMenu(header, popup, clickingColumn);
            for (int i = 0; i < popup.getComponentCount(); i++) {
                String menuItemName = popup.getComponent(i).getName();
                if (!(CONTEXT_MENU_COLLAPSE.equals(menuItemName)
                        || CONTEXT_MENU_COLLAPSE_ALL.equals(menuItemName)
                        || CONTEXT_MENU_EXPAND.equals(menuItemName)
                        || CONTEXT_MENU_EXPAND_ALL.equals(menuItemName)
                        || CONTEXT_MENU_GROUP.equals(menuItemName)
                        || CONTEXT_MENU_UNGROUP.equals(menuItemName))) {

                    popup.remove(popup.getComponent(i));

                }
            }
        }
    });

    aggregateTable.getAggregateTableModel().setSummaryMode(true);

    aggregateTable.aggregate(aggregateColumns);
    aggregateTable.setShowContextMenu(false);

    expandAllButLast();
    setupButtonColumn();

    JScrollPane jsp = new JScrollPane(aggregateTable);
    jsp.setPreferredSize(PREFERRED_SIZE);

    JPanel bp = new JPanel();

    bp.setLayout(new BoxLayout(bp, BoxLayout.X_AXIS));
    JButton closeButton = new JButton(IconFactory.getInstance().getIcon(IconFactory.StandardIcon.CLOSE));
    closeButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent ae) {
            unsplitScreen();
        }
    });
    bp.add(Box.createHorizontalGlue());
    bp.add(title);
    bp.add(Box.createHorizontalGlue());
    bp.add(closeButton);
    innerPanel.add(bp);
    innerPanel.add(jsp);
    reaggregate();
    innerPanel.revalidate();
    innerPanel.repaint();
}

From source file:org.wandora.application.gui.OccurrenceTableSingleType.java

/** Creates a new instance of OccurrenceTableSingleType */
public OccurrenceTableSingleType(Topic topic, Topic type, Options options, Wandora wandora)
        throws TopicMapException {
    this.wandora = wandora;
    this.topic = topic;
    TopicMap tm = wandora.getTopicMap();

    try {//from w  w  w  .j a v a 2 s  .  c  o m
        Options opts = options;
        if (opts == null)
            opts = wandora.getOptions();
        if (opts != null) {
            tableType = opts.get(VIEW_OPTIONS_KEY);
            if (tableType == null || tableType.length() == 0)
                tableType = VIEW_SCHEMA;

            defaultRowHeight = opts.getInt(ROW_HEIGHT_OPTIONS_KEY);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    this.type = type;

    HashSet<Topic> langSet = new LinkedHashSet();
    if (VIEW_USED.equalsIgnoreCase(tableType) || VIEW_USED_AND_SCHEMA.equalsIgnoreCase(tableType)) {
        Hashtable<Topic, String> occs = null;
        Topic langTopic = null;
        occs = topic.getData(type);
        for (Enumeration<Topic> keys = occs.keys(); keys.hasMoreElements();) {
            langTopic = keys.nextElement();
            langSet.add(langTopic);
        }
    }
    if (VIEW_SCHEMA.equalsIgnoreCase(tableType) || VIEW_USED_AND_SCHEMA.equalsIgnoreCase(tableType)) {
        Collection<Topic> langTopics = tm.getTopicsOfType(LANGUAGE_SI);
        langSet.addAll(langTopics);
    }

    langs = langSet.toArray(new Topic[langSet.size()]);
    data = new String[langs.length];
    originalData = new String[langs.length];
    colors = new Color[langs.length];

    for (int j = 0; j < langs.length; j++) {
        if (langs[j] != null) {
            data[j] = topic.getData(type, langs[j]);
            if (data[j] == null)
                data[j] = "";
            originalData[j] = data[j];
            colors[j] = wandora.topicHilights.getOccurrenceColor(topic, type, langs[j]);
        }
    }

    dataModel = new DataTableModel();
    sorter = new TableRowSorter(dataModel);

    final TableCellRenderer oldRenderer = this.getTableHeader().getDefaultRenderer();

    this.getTableHeader().setPreferredSize(new Dimension(100, 23));
    this.getTableHeader().setDefaultRenderer(new TableCellRenderer() {
        @Override
        public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                boolean hasFocus, int row, int column) {
            Component c = oldRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                    column);
            return c;
        }
    });

    this.setAutoCreateColumnsFromModel(false);

    TableColumn column = new TableColumn(0, 40, new TopicCellRenderer(), new TopicCellEditor());
    this.addColumn(column);
    column = new TableColumn(1, 400, new DataCellRenderer(), new DataCellEditor());
    this.addColumn(column);
    this.setTableHeader(this.getTableHeader());

    this.setModel(dataModel);
    this.setRowSorter(sorter);
    sorter.setSortsOnUpdates(true);

    updateRowHeights();

    popupStruct = WandoraMenuManager.getOccurrenceTableMenu(this, options);
    JPopupMenu popup = UIBox.makePopupMenu(popupStruct, wandora);
    this.setComponentPopupMenu(popup);
    this.addMouseListener(this);

    this.setColumnSelectionAllowed(false);
    this.setRowSelectionAllowed(false);
    this.setDragEnabled(true);
    this.setTransferHandler(new OccurrencesTableTransferHandler());
    this.setDropMode(DropMode.ON);
    this.createDefaultTableSelectionModel();
}