Example usage for javax.swing.table TableCellRenderer getTableCellRendererComponent

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

Introduction

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

Prototype

Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
        int row, int column);

Source Link

Document

Returns the component used for drawing the cell.

Usage

From source file:logdruid.ui.table.EventRecordingEditorTable.java

private void initColumnSizes(JTable theTable) {
    MyTableModel model = (MyTableModel) theTable.getModel();
    TableColumn column = null;/*from w w w  .j  a  va 2s .  c  o m*/
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    TableCellRenderer headerRenderer = theTable.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < 6; i++) {
        column = theTable.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        cellWidth = comp.getPreferredSize().width;

        if (DEBUG) {
            logger.info("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth
                    + "; cellWidth = " + cellWidth);
        }

        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:logdruid.ui.mainpanel.MetadataRecordingSelectorPanel.java

private void initColumnSizes(JTable theTable) {
    MyTableModel model = (MyTableModel) theTable.getModel();
    TableColumn column = null;//from  ww  w  .  j a v  a  2  s .co  m
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    // Object[] longValues = model.longValues;
    TableCellRenderer headerRenderer = theTable.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < 4; i++) {
        column = theTable.getColumnModel().getColumn(i);
        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;
        cellWidth = comp.getPreferredSize().width;
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:logdruid.ui.RecordingList.java

private void initColumnSizes(JTable theTable) {
    MyTableModel2 model = (MyTableModel2) theTable.getModel();
    TableColumn column = null;//from ww  w .jav a 2  s .c om
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    // Object[] longValues = model.longValues;
    TableCellRenderer headerRenderer = theTable.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < 4; i++) {
        column = theTable.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;
        cellWidth = comp.getPreferredSize().width;
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:logdruid.ui.DateEditor.java

private void initColumnSizes(JTable theTable) {
    MyTableModel2 model = (MyTableModel2) theTable.getModel();
    TableColumn column = null;/*from   ww  w.j a  v a 2 s .  co  m*/
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;
    // Object[] longValues = model.longValues;
    TableCellRenderer headerRenderer = theTable.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < 3; i++) {
        column = theTable.getColumnModel().getColumn(i);

        comp = headerRenderer.getTableCellRendererComponent(null, column.getHeaderValue(), false, false, 0, 0);
        headerWidth = comp.getPreferredSize().width;

        /*
         * comp = table.getDefaultRenderer(model.getColumnClass(i)).
         * getTableCellRendererComponent( table, longValues[i], false,
         * false, 0, i);
         */
        cellWidth = comp.getPreferredSize().width;

        if (DEBUG) {
            logger.info("Initializing width of column " + i + ". " + "headerWidth = " + headerWidth
                    + "; cellWidth = " + cellWidth);
        }

        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

From source file:modnlp.capte.AlignmentInterfaceWS.java

public JTable autoResizeColWidth(JTable table, DefaultTableModel model) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setModel(model);//from w ww.j  a  v  a  2  s . com

    int margin = 5;

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

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

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

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

        width = comp.getPreferredSize().width;

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

        // Add margin
        width += 2 * margin;

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

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

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

    return table;
}

From source file:edu.ku.brc.specify.tasks.subpane.ESResultsTablePanel.java

/**
 * @param table/*from  w  ww  .j  a v  a 2  s.co m*/
 * @param model
 */
protected void autoResizeColWidth(final JTable table, final DefaultTableModel model) {
    table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
    table.setModel(model);

    int margin = 5;

    DefaultTableColumnModel colModel = (DefaultTableColumnModel) table.getColumnModel();

    int preferredWidthTotal = 0;
    int renderedWidthTotal = 0;
    int[] colWidths = new int[table.getColumnCount()];
    int[] strWidths = new int[table.getColumnCount()];
    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        TableColumn col = colModel.getColumn(vColIndex);
        int width = 0;

        TableCellRenderer headerRenderer = col.getHeaderRenderer();
        if (headerRenderer instanceof JLabel) {
            ((JLabel) headerRenderer).setHorizontalAlignment(SwingConstants.CENTER);
        }

        // Get width of column header
        TableCellRenderer renderer = col.getCellRenderer();
        if (renderer == null) {
            renderer = table.getTableHeader().getDefaultRenderer();
        }

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

        width = comp.getPreferredSize().width;

        // Get maximum width of column data
        int strWidth = 0;
        boolean isString = model.getColumnClass(i) == String.class;
        for (int r = 0; r < table.getRowCount(); r++) {
            renderer = table.getCellRenderer(r, vColIndex);
            Object objVal = table.getValueAt(r, vColIndex);
            if (isString && objVal != null) {
                strWidth = Math.max(strWidth, ((String) objVal).length());
            }
            comp = renderer.getTableCellRendererComponent(table, objVal, false, false, r, vColIndex);
            width = Math.max(width, comp.getPreferredSize().width);
        }

        // Add margin
        width += 2 * margin;

        preferredWidthTotal += col.getPreferredWidth();
        colWidths[i] = width;
        strWidths[i] = strWidth;

        renderedWidthTotal += width;
    }

    if (renderedWidthTotal > preferredWidthTotal) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            TableColumn col = colModel.getColumn(i);
            TableCellRenderer renderer = col.getCellRenderer();
            if (renderer != null) {
                ((JLabel) renderer).setHorizontalAlignment(
                        strWidths[i] > 20 ? SwingConstants.LEFT : SwingConstants.CENTER);
                //((JLabel)renderer).setHorizontalAlignment(SwingConstants.LEFT);
            }

            if (model.getColumnCount() > 3 && renderedWidthTotal > preferredWidthTotal) {
                col.setPreferredWidth(colWidths[i]);
            }
        }
    }

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

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

From source file:dataviewer.DataViewer.java

private void renderData(DefaultTableModel model) {
    tb_data.setVisible(false);//w  ww . j  av a  2s. c  om

    tb_data.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
        @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);
            c.setBackground(row % 2 == 0 ? Color.WHITE : new Color(240, 240, 240));

            if (table.isCellSelected(row, column)) {
                c.setBackground(new Color(200, 0, 0));
                c.setForeground(Color.white);
            } else if (table.isRowSelected(row)) {
                c.setBackground(new Color(0, 0, 200));
                c.setForeground(Color.white);
            } else {
                c.setForeground(Color.black);
            }
            return c;
        }
    });

    tb_data.setGridColor(new Color(220, 220, 220));
    tb_data.setShowVerticalLines(true);
    tb_data.setModel(model);

    for (int i = 0; i < model.getColumnCount(); ++i) {
        if (model.getColumnName(i).equals("_N_")) {
            TableRowSorter trs = new TableRowSorter(model);
            trs.setComparator(i, new IntComparator());
            tb_data.setRowSorter(trs);
        }
    }

    for (int j = 0; j < tb_data.getColumnCount(); j++) {
        int width = 0;
        TableColumn col = tb_data.getColumnModel().getColumn(j);
        TableCellRenderer renderer = tb_data.getTableHeader().getDefaultRenderer();
        Component comp = renderer.getTableCellRendererComponent(tb_data, col.getHeaderValue(), false, false, 0,
                0);
        width = Math.max(comp.getPreferredSize().width, width);
        for (int i = 0; i < tb_data.getRowCount(); i++) {
            renderer = tb_data.getCellRenderer(i, j);
            comp = tb_data.prepareRenderer(renderer, i, j);
            width = Math.max(comp.getPreferredSize().width, width);
        }
        tb_data.getColumnModel().getColumn(j).setPreferredWidth(width + 20);
    }

    tb_data.setVisible(true);

}

From source file:it.iit.genomics.cru.igb.bundles.mi.view.MITable.java

public MITable(MITableModel model, IgbService service, final MIQuery query) {
    super(model);

    this.query = query;
    igbLogger = IGBLogger.getInstance(query.getLabel());
    this.igbService = service;

    this.SymSelectionListener = new MouseListener() {

        @SuppressWarnings("unchecked")
        @Override/*from ww w .  j ava  2  s . com*/
        public void mouseClicked(MouseEvent e) {

            if (e.getComponent().isEnabled() && e.getButton() == MouseEvent.BUTTON1) {

                if (getSelectedRow() >= 0) {
                    int modelRow = convertRowIndexToModel(getSelectedRow());

                    MIResult interaction = ((MITableModel) getModel()).getResult(modelRow);

                    structuresPanel.setCurrentInteraction(interaction);
                }

                MITable table = (MITable) e.getComponent();
                int modelRow = convertRowIndexToModel(table.getSelectedRow());
                int column = table.getSelectedColumn();

                if (e.getClickCount() == 1) {
                    if (column == MITableModel.TRACK_COLUMN) {
                        Object value = table.getValueAt(table.getSelectedRow(), column);

                        if (value instanceof JButton) {
                            MIResult result = ((MITableModel) table.getModel()).getResult(modelRow);

                            TypeContainerAnnot interactorTrack = result.createTrack();

                            igbService.addTrack(interactorTrack, interactorTrack.getID());

                            igbService.getSeqMapView().updatePanel();

                            for (TierGlyph t : igbService.getAllTierGlyphs()) {

                                if (TierGlyph.TierType.ANNOTATION.equals(t.getTierType())
                                        && (t.getAnnotStyle().getTrackName().equals(interactorTrack.getID()))) {

                                    SimpleTrackStyle style = new SimpleTrackStyle(interactorTrack.getID(),
                                            false) {

                                        @Override
                                        public boolean drawCollapseControl() {
                                            return false;
                                        }
                                    };

                                    t.getAnnotStyle().copyPropertiesFrom(style);
                                    t.getAnnotStyle().setColorProvider(new RGB());
                                    interactorTrack.setProperty(TrackLineParser.ITEM_RGB, "on");
                                }
                            }

                            igbService.getSeqMapView().updatePanel();

                            ((JButton) value).setText(interactorTrack.getID());
                            ((JButton) value).setEnabled(false);

                            updateUI();
                        }
                    }
                } else {
                    // symmetry: zoom-in
                    if (column == MITableModel.SYMS1_COLUMN) {
                        MoleculeEntry entry = ((MITableModel) table.getModel()).getResult(modelRow)
                                .getInteractor1();
                        if (query.getTaxid().equals(entry.getTaxid())) {
                            Collection<SeqSymmetry> syms = ((MITableModel) table.getModel()).getResult(modelRow)
                                    .getSymmetries1();
                            zoomToSym(syms);
                        }
                    } else if (column == MITableModel.SYMS2_COLUMN) {
                        MoleculeEntry entry = ((MITableModel) table.getModel()).getResult(modelRow)
                                .getInteractor2();
                        if (query.getTaxid().equals(entry.getTaxid())) {
                            Collection<SeqSymmetry> syms = ((MITableModel) table.getModel()).getResult(modelRow)
                                    .getSymmetries2();
                            zoomToSym(syms);
                        }
                    }

                    // Protein: link to uniprot
                    if (column == MITableModel.INTERACTOR1_COLUMN
                            || column == MITableModel.INTERACTOR2_COLUMN) {

                        MIResult miResult = ((MITableModel) table.getModel()).getResult(modelRow);

                        String id;
                        String taxid;

                        MoleculeEntry interactor;
                        if (column == MITableModel.INTERACTOR1_COLUMN) {
                            interactor = miResult.getInteractor1();
                        } else {
                            interactor = miResult.getInteractor2();
                        }

                        taxid = interactor.getTaxid();

                        String query;
                        String anchor = "";
                        switch (taxid) {
                        case MoleculeEntry.TAXID_DNA:
                        case MoleculeEntry.TAXID_RNA:
                            if (miResult.getInteractionStructures().isEmpty()) {
                                return;
                            }
                            query = "http://www.pdb.org/pdb/explore/explore.do?structureId="
                                    + miResult.getInteractionStructures().iterator().next().getStructureID();
                            break;
                        case MoleculeEntry.TAXID_LIGAND:
                            if (miResult.getInteractionStructures().isEmpty()) {
                                return;
                            }
                            query = DrugBankMapper.getInstance().isDrug(interactor.getGeneName())
                                    ? DrugBankMapper.getInstance().getDrugBankLink(interactor.getGeneName())
                                    : "http://www.ebi.ac.uk/pdbe-srv/pdbechem/chemicalCompound/show/"
                                            + interactor.getGeneName();
                            break;
                        case MoleculeEntry.TAXID_MODIFICATION:
                            query = "http://www.uniprot.org/uniprot/"
                                    + miResult.getInteractor1().getUniprotAc();
                            anchor = "#ptm_processing";
                            break;
                        default:
                            id = interactor.getUniprotAc();
                            query = "http://www.uniprot.org/uniprot/" + id;
                            break;
                        }
                        try {
                            URI uri = new URI(URIUtil.encodeQuery(query) + anchor);

                            Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
                            if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
                                desktop.browse(uri);
                            }
                        } catch (IOException ioe) {
                            JOptionPane.showMessageDialog(null, "Cannot reach Uniprot website.");
                            return;
                        } catch (URISyntaxException ue) {
                            JOptionPane.showMessageDialog(null, "Cannot reach Uniprot website: " + query);
                        }
                    }

                    // interaction type: link to psicquic
                    if (column == MITableModel.INTERACTION_TYPE_COLUMN) {

                        MIResult miResult = ((MITableModel) table.getModel()).getResult(modelRow);

                        String queryURL;
                        String idA = miResult.getInteractor1().getUniprotAc();
                        String idB = miResult.getInteractor2().getUniprotAc();

                        if (null == miResult.getPsicquicUrl()) {
                            // from the structure database
                            if (query.searchDSysMap()) {
                                queryURL = "http://http://dsysmap.irbbarcelona.org/results.php?type=proteins&neigh=2&value="
                                        + idA + "," + idB;
                            } else if (query.searchInteractome3D()) {
                                try {
                                    queryURL = "http://interactome3d.irbbarcelona.org/interaction.php?ids="
                                            + idA + ";" + idB + "&dataset="
                                            + it.iit.genomics.cru.bridges.interactome3d.ws.Utils
                                                    .getDataset(query.getTaxid());
                                } catch (Interactome3DException e3d) {
                                    // it will never happend: if the taxid was not known by 
                                    // I3D, we wouldn't have an interaction
                                    return;
                                }

                            } else {
                                return;
                            }
                        } else {

                            if (false == idA.equals(idB)) {
                                queryURL = miResult.getPsicquicUrl() + "query/id:"
                                        + miResult.getInteractor1().getUniprotAc() + "* AND id:"
                                        + miResult.getInteractor2().getUniprotAc() + "*";
                            } else {
                                queryURL = miResult.getPsicquicUrl() + "query/idA:"
                                        + miResult.getInteractor1().getUniprotAc() + "* AND idB:"
                                        + miResult.getInteractor2().getUniprotAc() + "*";
                            }
                        }
                        try {
                            URI uri = new URI(URIUtil.encodeQuery(queryURL));

                            Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
                            if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
                                desktop.browse(uri);
                            }
                        } catch (IOException ioe) {
                            JOptionPane.showMessageDialog(null, "Cannot reach psicquic server.");
                        } catch (URISyntaxException ue) {
                            JOptionPane.showMessageDialog(null, "Cannot reach psicquic server: " + queryURL);
                        }

                    }
                }
            }

        }

        @Override
        public void mousePressed(MouseEvent me) {
        }

        @Override
        public void mouseReleased(MouseEvent me) {
        }

        @Override
        public void mouseEntered(MouseEvent me) {
        }

        @Override
        public void mouseExited(MouseEvent me) {
        }
    };

    TableRowSorter<MITableModel> sorter = new MITableRowSorter(model);
    setRowSorter(sorter);

    sorter.setRowFilter(evidenceRowFilter());
    model.fireTableDataChanged();
    this.getTableHeader().setReorderingAllowed(false);

    TableCellRenderer rend = getTableHeader().getDefaultRenderer();
    TableColumnModel tcm = getColumnModel();
    for (int j = 0; j < tcm.getColumnCount(); j += 1) {
        TableColumn tc = tcm.getColumn(j);
        TableCellRenderer rendCol = tc.getHeaderRenderer(); // likely null
        if (rendCol == null) {
            rendCol = rend;
        }
        Component c = rendCol.getTableCellRendererComponent(this, tc.getHeaderValue(), false, false, 0, j);
        tc.setPreferredWidth(c.getPreferredSize().width);
    }

    TableCellRenderer buttonRenderer = new JTableButtonRenderer();

    getColumn(model.getColumnName(MITableModel.TRACK_COLUMN)).setCellRenderer(buttonRenderer);

    getColumn(model.getColumnName(MITableModel.SYMS1_COLUMN)).setCellRenderer(new GeneRenderer());
    getColumn(model.getColumnName(MITableModel.SYMS2_COLUMN)).setCellRenderer(new GeneRenderer());

    getColumn(model.getColumnName(MITableModel.INTERACTOR1_COLUMN)).setCellRenderer(new MoleculeRenderer());
    getColumn(model.getColumnName(MITableModel.INTERACTOR2_COLUMN)).setCellRenderer(new MoleculeRenderer());

    getColumn(model.getColumnName(MITableModel.INTERACTION_TYPE_COLUMN))
            .setCellRenderer(new EvidenceRenderer());

    getColumn(model.getColumnName(MITableModel.STRUCTURES_COLUMN)).setCellRenderer(new StructuresRenderer());

    setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);

    int smallWidth = 75;
    int mediumWidth = 120;
    int largeWidth = 200;
    getColumnModel().getColumn(MITableModel.TRACK_COLUMN).setMinWidth(smallWidth);

    getColumnModel().getColumn(MITableModel.STRUCTURES_COLUMN).setMinWidth(smallWidth);
    getColumnModel().getColumn(MITableModel.STRUCTURES_COLUMN).setMaxWidth(smallWidth);
    getColumnModel().getColumn(MITableModel.STRUCTURES_COLUMN).setPreferredWidth(smallWidth);

    addMouseListener(SymSelectionListener);

    getSelectionModel().addListSelectionListener(new RowSelectionListener());

}

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;//  w w w  .  ja  va 2s . com

    // 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:edu.ku.brc.ui.tmanfe.SpreadSheet.java

/**
  * //from  w w w.j a  v a 2  s . c o m
  */
protected void buildSpreadsheet() {

    this.setShowGrid(true);

    int numRows = model.getRowCount();

    scrollPane = new JScrollPane(this, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
            ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    final SpreadSheet ss = this;
    JButton cornerBtn = UIHelper.createIconBtn("Blank", IconManager.IconSize.Std16, "SelectAll",
            new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    ss.selectAll();
                }
            });
    cornerBtn.setEnabled(true);
    scrollPane.setCorner(ScrollPaneConstants.UPPER_LEFT_CORNER, cornerBtn);

    // Allows row and collumn selections to exit at the same time
    setCellSelectionEnabled(true);

    setRowSelectionAllowed(true);
    setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

    addMouseListener(new MouseAdapter() {
        /* (non-Javadoc)
         * @see java.awt.event.MouseAdapter#mousePressed(java.awt.event.MouseEvent)
         */
        @SuppressWarnings("synthetic-access")
        @Override
        public void mouseReleased(MouseEvent e) {
            // XXX For Java 5 Bug
            prevRowSelInx = getSelectedRow();
            prevColSelInx = getSelectedColumn();

            if (e.getClickCount() == 2) {
                int rowIndexStart = getSelectedRow();
                int colIndexStart = getSelectedColumn();

                ss.editCellAt(rowIndexStart, colIndexStart);
                if (ss.getEditorComponent() != null && ss.getEditorComponent() instanceof JTextComponent) {
                    ss.getEditorComponent().requestFocus();

                    final JTextComponent txtComp = (JTextComponent) ss.getEditorComponent();
                    String txt = txtComp.getText();
                    FontMetrics fm = txtComp.getFontMetrics(txtComp.getFont());
                    int x = e.getPoint().x - ss.getEditorComponent().getBounds().x - 1;
                    int prevWidth = 0;
                    for (int i = 0; i < txt.length(); i++) {

                        int width = fm.stringWidth(txt.substring(0, i));
                        int basePlusHalf = prevWidth + (int) (((width - prevWidth) / 2) + 0.5);
                        //System.out.println(prevWidth + " X[" + x + "] " + width+" ["+txt.substring(0, i)+"] " + i + " " + basePlusHalf);
                        //System.out.println(" X[" + x + "] " + prevWidth + " - "+ basePlusHalf+" - " + width+" ["+txt.substring(0, i)+"] " + i);
                        if (x < width) {
                            // Clearing the selection is needed for Window for some reason
                            final int inx = i + (x <= basePlusHalf ? -1 : 0);
                            SwingUtilities.invokeLater(new Runnable() {
                                @SuppressWarnings("synthetic-access")
                                public void run() {
                                    txtComp.setSelectionStart(0);
                                    txtComp.setSelectionEnd(0);
                                    txtComp.setCaretPosition(inx > 0 ? inx : 0);
                                }
                            });
                            break;
                        }
                        prevWidth = width;
                    }
                }
            }
        }
    });

    // Create a row-header to display row numbers.
    // This row-header is made of labels whose Borders,
    // Foregrounds, Backgrounds, and Fonts must be
    // the one used for the table column headers.
    // Also ensure that the row-header labels and the table
    // rows have the same height.

    //i have no idea WHY this has to be called.  i rearranged
    //the table and find replace panel, 
    // i started getting an array index out of
    //bounds on the column header ON MAC ONLY.  
    //tried firing this off, first and it fixed the problem.//meg
    this.getModel().fireTableStructureChanged();

    /*
     * Create the Row Header Panel
     */
    rowHeaderPanel = new JPanel((LayoutManager) null);

    if (getColumnModel().getColumnCount() > 0) {
        TableColumn column = getColumnModel().getColumn(0);
        TableCellRenderer renderer = getTableHeader().getDefaultRenderer();
        if (renderer == null) {
            renderer = column.getHeaderRenderer();
        }

        Component cellRenderComp = renderer.getTableCellRendererComponent(this, column.getHeaderValue(), false,
                false, -1, 0);
        cellFont = cellRenderComp.getFont();

    } else {
        cellFont = (new JLabel()).getFont();
    }

    // Calculate Row Height
    cellBorder = (Border) UIManager.getDefaults().get("TableHeader.cellBorder");
    Insets insets = cellBorder.getBorderInsets(tableHeader);
    FontMetrics metrics = getFontMetrics(cellFont);

    rowHeight = insets.bottom + metrics.getHeight() + insets.top;
    rowLabelWidth = metrics.stringWidth("9999") + insets.right + insets.left;

    Dimension dim = new Dimension(rowLabelWidth, rowHeight * numRows);
    rowHeaderPanel.setPreferredSize(dim); // need to call this when no layout manager is used.

    rhCellMouseAdapter = new RHCellMouseAdapter(this);

    // Adding the row header labels
    for (int ii = 0; ii < numRows; ii++) {
        addRow(ii, ii + 1, false);
    }

    JViewport viewPort = new JViewport();
    dim.height = rowHeight * numRows;
    viewPort.setViewSize(dim);
    viewPort.setView(rowHeaderPanel);
    scrollPane.setRowHeader(viewPort);

    // Experimental from the web, but I think it does the trick.
    addKeyListener(new KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent e) {
            if (!ss.isEditing() && !e.isActionKey() && !e.isControlDown() && !e.isMetaDown() && !e.isAltDown()
                    && e.getKeyCode() != KeyEvent.VK_SHIFT && e.getKeyCode() != KeyEvent.VK_TAB
                    && e.getKeyCode() != KeyEvent.VK_ENTER) {
                log.error("Grabbed the event as input");

                int rowIndexStart = getSelectedRow();
                int colIndexStart = getSelectedColumn();

                if (rowIndexStart == -1 || colIndexStart == -1)
                    return;

                ss.editCellAt(rowIndexStart, colIndexStart);
                Component c = ss.getEditorComponent();
                if (c instanceof JTextComponent)
                    ((JTextComponent) c).setText("");
            }
        }
    });

    resizeAndRepaint();

    // Taken from a JavaWorld Example (But it works)
    KeyStroke cut = KeyStroke.getKeyStroke(KeyEvent.VK_X, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
            false);
    KeyStroke copy = KeyStroke.getKeyStroke(KeyEvent.VK_C, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(),
            false);
    KeyStroke paste = KeyStroke.getKeyStroke(KeyEvent.VK_V,
            Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false);

    Action ssAction = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            SpreadSheet.this.actionPerformed(e);
        }
    };

    getInputMap().put(cut, "Cut");
    getActionMap().put("Cut", ssAction);

    getInputMap().put(copy, "Copy");
    getActionMap().put("Copy", ssAction);

    getInputMap().put(paste, "Paste");
    getActionMap().put("Paste", ssAction);

    ((JMenuItem) UIRegistry.get(UIRegistry.COPY)).addActionListener(this);
    ((JMenuItem) UIRegistry.get(UIRegistry.CUT)).addActionListener(this);
    ((JMenuItem) UIRegistry.get(UIRegistry.PASTE)).addActionListener(this);

    setSortOrderCycle(SortOrder.ASCENDING, SortOrder.DESCENDING, SortOrder.UNSORTED);
}