Example usage for javax.swing.table TableColumn getHeaderValue

List of usage examples for javax.swing.table TableColumn getHeaderValue

Introduction

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

Prototype

public Object getHeaderValue() 

Source Link

Document

Returns the Object used as the value for the header renderer.

Usage

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

private void updateVariablesShown() {
    String tableName = rangeFilterPanel.getSelectedTable();
    variablesToShow = variableChooserPanel.getSelectedVariableNames(tableName);
    // first set all invisible
    Enumeration<TableColumn> tcs = tableColumnModel.getColumns(false);
    while (tcs.hasMoreElements()) {
        TableColumn column = tcs.nextElement();
        tableColumnModel.setColumnVisible(column, variablesToShow.contains(column.getHeaderValue().toString()));
    }//from   www  .j  ava 2  s .c  o  m
}

From source file:dataviewer.DataViewer.java

private void renderData(DefaultTableModel model) {
    tb_data.setVisible(false);/*from  w w  w . j  a  v a2s.co  m*/

    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// w w w  .  ja v  a2  s .  co  m
        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:display.containers.FileManager.java

private void setColumnWidth(int column, int width) {
    TableColumn tableColumn = table.getColumnModel().getColumn(column);
    if (width < 0) {
        // use the preferred width of the header..
        JLabel label = new JLabel((String) tableColumn.getHeaderValue());
        Dimension preferred = label.getPreferredSize();
        // altered 10->14 as per camickr comment.
        width = (int) preferred.getWidth() + 14;
    }//  w  ww  .j av  a2s  .  c  o  m
    tableColumn.setPreferredWidth(width);
    tableColumn.setMaxWidth(width);
    tableColumn.setMinWidth(width);
}

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

/**
 * @param table//from  w  w  w .  j av  a  2s .c o  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:edu.ku.brc.ui.tmanfe.SpreadSheet.java

/**
  * //from w  w w .  j a  v a2  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);
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * @param table/*from  w  ww . jav a  2  s. c  o m*/
 * @param model
 * @return
 */
public static JTable 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()];
    for (int i = 0; i < table.getColumnCount(); i++) {
        int vColIndex = i;
        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;

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

        renderedWidthTotal += width;
    }

    if (renderedWidthTotal > preferredWidthTotal) {
        for (int i = 0; i < table.getColumnCount(); i++) {
            colModel.getColumn(i).setPreferredWidth(colWidths[i]);
        }
    }

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

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

    return table;
}

From source file:edu.ku.brc.ui.UIHelper.java

/**
 * Calculates and sets the each column to it preferred size.  NOTE: This
 * method also sets the table height to 10 rows.
 * //  www.  j  av  a  2s  . c  o m
 * @param table the table to fix up
 * @param numRowsHeight the number of rows to make the table height (or null not to set it)
 */
public static void calcColumnWidths(final JTable table, final Integer numRowsHeight, final Integer maxWidth) {
    if (table != null) {
        JTableHeader header = table.getTableHeader();

        TableCellRenderer defaultHeaderRenderer = null;

        if (header != null) {
            defaultHeaderRenderer = header.getDefaultRenderer();
        }

        TableColumnModel columns = table.getColumnModel();
        TableModel data = table.getModel();

        int margin = columns.getColumnMargin(); // only JDK1.3

        int rowCount = data.getRowCount();

        int totalWidth = 0;

        for (int i = columns.getColumnCount() - 1; i >= 0; --i) {
            TableColumn column = columns.getColumn(i);

            int columnIndex = column.getModelIndex();

            int width = -1;

            TableCellRenderer h = column.getHeaderRenderer();

            if (h == null)
                h = defaultHeaderRenderer;

            if (h != null) // Not explicitly impossible
            {
                Component c = h.getTableCellRendererComponent(table, column.getHeaderValue(), false, false, -1,
                        i);

                width = c.getPreferredSize().width;
            }

            for (int row = rowCount - 1; row >= 0; --row) {
                TableCellRenderer r = table.getCellRenderer(row, i);

                Component c = r.getTableCellRendererComponent(table, data.getValueAt(row, columnIndex), false,
                        false, row, i);

                width = Math.max(width, c.getPreferredSize().width + 10); // adding an arbitray 10 pixels to make it look nicer

                if (maxWidth != null) {
                    width = Math.min(width, maxWidth);
                }
            }

            if (width >= 0) {
                column.setPreferredWidth(width + margin); // <1.3: without margin
            } else {
                // ???
            }

            totalWidth += column.getPreferredWidth();
        }

        // If you like; This does not make sense for two many columns!
        Dimension size = table.getPreferredScrollableViewportSize();
        //if (totalWidth > size.width)
        {
            if (numRowsHeight != null) {
                size.height = Math.min(size.height, table.getRowHeight() * numRowsHeight);
            }
            size.width = totalWidth;
            table.setPreferredScrollableViewportSize(size);
        }
    }
}

From source file:edu.ku.brc.af.ui.forms.TableViewObj.java

/**
 * Adjust all the column width for the data in the column, this may be handles with JDK 1.6 (6.)
 * @param tableArg the table that should have it's columns adjusted
 *//*from w w  w  .  j a  va 2 s.  co  m*/
private void initColumnSizes(final JTable tableArg) {
    ColTableModel tblModel = (ColTableModel) tableArg.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;

    TableCellRenderer headerRenderer = tableArg.getTableHeader().getDefaultRenderer();

    for (int i = 0; i < tblModel.getColumnCount(); i++) {
        column = tableArg.getColumnModel().getColumn(i);

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

        comp = tableArg.getDefaultRenderer(tblModel.getColumnClass(i)).getTableCellRendererComponent(tableArg,
                tblModel.getValueAt(0, i), false, false, 0, i);

        cellWidth = comp.getPreferredSize().width;

        /*
        if (DEBUG) {
        System.out.println("Initializing width of column "
                           + i + ". "
                           + "headerWidth = " + headerWidth
                           + "; cellWidth = " + cellWidth);
        }*/

        //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
        column.setPreferredWidth(Math.max(headerWidth, cellWidth));
    }
}

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

/**
 * Adjust all the column width for the data in the column, this may be handles with JDK 1.6 (6.)
 * @param tableArg the table that should have it's columns adjusted
 */// w w  w .ja  v  a  2s . c  om
private void initColumnSizes(final JTable tableArg, final JButton theSaveBtn) throws Exception {
    TableModel tblModel = tableArg.getModel();
    TableColumn column = null;
    Component comp = null;
    int headerWidth = 0;
    int cellWidth = 0;

    Element uploadDefs = null;
    if (WorkbenchTask.isCustomizedSchema()) {
        uploadDefs = XMLHelper.readFileToDOM4J(
                new File(UIRegistry.getAppDataDir() + File.separator + "specify_workbench_upload_def.xml"));
    } else {
        uploadDefs = XMLHelper.readDOMFromConfigDir("specify_workbench_upload_def.xml");
    }

    //UIRegistry.getInstance().hookUpUndoableEditListener(cellEditor);

    Vector<WorkbenchTemplateMappingItem> wbtmis = new Vector<WorkbenchTemplateMappingItem>();
    wbtmis.addAll(workbench.getWorkbenchTemplate().getWorkbenchTemplateMappingItems());
    Collections.sort(wbtmis);

    DBTableIdMgr databaseSchema = WorkbenchTask.getDatabaseSchema();

    columnMaxWidths = new Integer[tableArg.getColumnCount()];
    for (int i = 0; i < wbtmis.size() /*tableArg.getColumnCount()*/; i++) {
        TableCellRenderer headerRenderer = tableArg.getColumnModel().getColumn(i).getHeaderRenderer();
        WorkbenchTemplateMappingItem wbtmi = wbtmis.elementAt(i);

        // Now go retrieve the data length
        int fieldWidth = WorkbenchDataItem.getMaxWBCellLength();
        DBTableInfo ti = databaseSchema.getInfoById(wbtmi.getSrcTableId());
        if (ti != null) {
            DBFieldInfo fi = ti.getFieldByName(wbtmi.getFieldName());
            if (fi != null) {
                wbtmi.setFieldInfo(fi);
                //System.out.println(fi.getName()+"  "+fi.getLength()+"  "+fi.getType());
                if (RecordTypeCodeBuilder.getTypeCode(fi) == null && fi.getLength() > 0) {
                    fieldWidth = Math.min(fi.getLength(), WorkbenchDataItem.getMaxWBCellLength());
                }
            } else {
                log.error("Can't find field with name [" + wbtmi.getFieldName() + "]");
            }
        } else {
            log.error("Can't find table [" + wbtmi.getSrcTableId() + "]");
        }
        columnMaxWidths[i] = new Integer(fieldWidth);
        GridCellEditor cellEditor = getCellEditor(wbtmi, fieldWidth, theSaveBtn, uploadDefs);
        column = tableArg.getColumnModel().getColumn(i);

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

        comp = tableArg.getDefaultRenderer(tblModel.getColumnClass(i)).getTableCellRendererComponent(tableArg,
                tblModel.getValueAt(0, i), false, false, 0, i);

        cellWidth = comp.getPreferredSize().width;

        //comp.setBackground(Color.WHITE);

        int maxWidth = headerWidth + 10;
        TableModel m = tableArg.getModel();
        FontMetrics fm = comp.getFontMetrics(comp.getFont());
        for (int row = 0; row < tableArg.getModel().getRowCount(); row++) {
            String text = m.getValueAt(row, i).toString();
            maxWidth = Math.max(maxWidth, fm.stringWidth(text) + 10);
            //log.debug(i+" "+maxWidth);
        }

        //XXX: Before Swing 1.1 Beta 2, use setMinWidth instead.
        //log.debug(Math.max(maxWidth, cellWidth));
        //log.debug(Math.min(Math.max(maxWidth, cellWidth), 400));
        column.setPreferredWidth(Math.min(Math.max(maxWidth, cellWidth), 400));

        column.setCellEditor(cellEditor);
    }
    //tableArg.setCellEditor(cellEditor);
}