Search in sources :

Example 36 with TableCellRenderer

use of javax.swing.table.TableCellRenderer in project cytoscape-api by cytoscape.

the class ColumnResizer method adjustColumnPreferredWidth.

/**
	 * Adjust one table column to its preferred width.
	 * @param table The table whose columns should be adjusted.
	 * @param col The column index.
	 * @param checkAllRows If false, only the preferred width of the column header is considered.
	 */
public static void adjustColumnPreferredWidth(final JTable table, final int col, final boolean checkAllRows) {
    // Get max width for cells in column and make that the preferred width
    int maxwidth = 0;
    if (checkAllRows) {
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer rend = table.getCellRenderer(row, col);
            Object value = table.getValueAt(row, col);
            Component comp = rend.getTableCellRendererComponent(table, value, false, false, row, col);
            maxwidth = Math.max(comp.getPreferredSize().width, maxwidth);
        }
    }
    // This version of the width set considers the column header's preferred width too
    TableColumn column = table.getColumnModel().getColumn(col);
    TableCellRenderer headerRenderer = column.getHeaderRenderer();
    if (headerRenderer == null)
        headerRenderer = table.getTableHeader().getDefaultRenderer();
    Object headerValue = column.getHeaderValue();
    Component headerComp = headerRenderer.getTableCellRendererComponent(table, headerValue, false, false, 0, col);
    maxwidth = Math.max(maxwidth, headerComp.getPreferredSize().width);
    // If the value is too big, adjust to fixed maximum value
    if (DEFLMAX_WIDTH < maxwidth)
        maxwidth = DEFLMAX_WIDTH;
    column.setPreferredWidth(maxwidth + 20);
}
Also used : TableCellRenderer(javax.swing.table.TableCellRenderer) Component(java.awt.Component) TableColumn(javax.swing.table.TableColumn)

Example 37 with TableCellRenderer

use of javax.swing.table.TableCellRenderer in project cytoscape-api by cytoscape.

the class AbstractVisualPropertyEditorTest method testGetDiscreteTableCellRenderer.

@Test
public void testGetDiscreteTableCellRenderer() {
    TableCellRenderer discreteTableCellRenderer = mock(TableCellRenderer.class);
    editor.discreteTableCellRenderer = discreteTableCellRenderer;
    assertEquals(discreteTableCellRenderer, editor.getDiscreteTableCellRenderer());
}
Also used : TableCellRenderer(javax.swing.table.TableCellRenderer) Test(org.junit.Test)

Example 38 with TableCellRenderer

use of javax.swing.table.TableCellRenderer in project beast-mcmc by beast-dev.

the class ColumnResizer method adjustColumnPreferredWidths.

public static void adjustColumnPreferredWidths(JTable table) {
    TableColumnModel columnModel = table.getColumnModel();
    for (int col = 0; col < table.getColumnCount(); col++) {
        int maxwidth = 0;
        for (int row = 0; row < table.getRowCount(); row++) {
            TableCellRenderer rend = table.getCellRenderer(row, col);
            Object value = table.getValueAt(row, col);
            Component comp = rend.getTableCellRendererComponent(table, value, false, false, row, col);
            maxwidth = Math.max(comp.getPreferredSize().width, maxwidth);
        }
        // END: row loop
        TableColumn column = columnModel.getColumn(col);
        TableCellRenderer headerRenderer = column.getHeaderRenderer();
        if (headerRenderer == null) {
            headerRenderer = table.getTableHeader().getDefaultRenderer();
        }
        Object headerValue = column.getHeaderValue();
        Component headerComp = headerRenderer.getTableCellRendererComponent(table, headerValue, false, false, 0, col);
        maxwidth = Math.max(maxwidth, headerComp.getPreferredSize().width);
        column.setPreferredWidth(maxwidth);
    }
// END: col loop
}
Also used : TableCellRenderer(javax.swing.table.TableCellRenderer) TableColumnModel(javax.swing.table.TableColumnModel) Component(java.awt.Component) TableColumn(javax.swing.table.TableColumn)

Example 39 with TableCellRenderer

use of javax.swing.table.TableCellRenderer in project JMRI by JMRI.

the class LightTableAction method createModel.

/**
     * Create the JTable DataModel, along with the changes for the specific case
     * of Lights.
     */
@Override
protected void createModel() {
    // load graphic state column display preference
    _graphicState = InstanceManager.getDefault(GuiLafPreferencesManager.class).isGraphicTableState();
    m = new BeanTableDataModel() {

        public static final int ENABLECOL = NUMCOLUMN;

        public static final int INTENSITYCOL = ENABLECOL + 1;

        public static final int EDITCOL = INTENSITYCOL + 1;

        protected String enabledString = Bundle.getMessage("ColumnHeadEnabled");

        protected String intensityString = Bundle.getMessage("ColumnHeadIntensity");

        @Override
        public int getColumnCount() {
            return NUMCOLUMN + 3;
        }

        @Override
        public String getColumnName(int col) {
            if (col == EDITCOL) {
                // no heading on "Edit"
                return "";
            }
            if (col == INTENSITYCOL) {
                return intensityString;
            }
            if (col == ENABLECOL) {
                return enabledString;
            } else {
                return super.getColumnName(col);
            }
        }

        @Override
        public Class<?> getColumnClass(int col) {
            if (col == EDITCOL) {
                return JButton.class;
            }
            if (col == INTENSITYCOL) {
                return Double.class;
            }
            if (col == ENABLECOL) {
                return Boolean.class;
            } else if (col == VALUECOL && _graphicState) {
                // use an image to show light state
                return JLabel.class;
            } else {
                return super.getColumnClass(col);
            }
        }

        @Override
        public int getPreferredWidth(int col) {
            // override default value for UserName column
            if (col == USERNAMECOL) {
                return new JTextField(16).getPreferredSize().width;
            }
            if (col == EDITCOL) {
                return new JTextField(6).getPreferredSize().width;
            }
            if (col == INTENSITYCOL) {
                return new JTextField(6).getPreferredSize().width;
            }
            if (col == ENABLECOL) {
                return new JTextField(6).getPreferredSize().width;
            } else {
                return super.getPreferredWidth(col);
            }
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            if (col == EDITCOL) {
                return true;
            }
            if (col == INTENSITYCOL) {
                return ((Light) getBySystemName((String) getValueAt(row, SYSNAMECOL))).isIntensityVariable();
            }
            if (col == ENABLECOL) {
                return true;
            } else {
                return super.isCellEditable(row, col);
            }
        }

        @Override
        public String getValue(String name) {
            Light l = lightManager.getBySystemName(name);
            if (l == null) {
                return ("Failed to find " + name);
            }
            int val = l.getState();
            switch(val) {
                case Light.ON:
                    return Bundle.getMessage("LightStateOn");
                case Light.INTERMEDIATE:
                    return Bundle.getMessage("LightStateIntermediate");
                case Light.OFF:
                    return Bundle.getMessage("LightStateOff");
                case Light.TRANSITIONINGTOFULLON:
                    return Bundle.getMessage("LightStateTransitioningToFullOn");
                case Light.TRANSITIONINGHIGHER:
                    return Bundle.getMessage("LightStateTransitioningHigher");
                case Light.TRANSITIONINGLOWER:
                    return Bundle.getMessage("LightStateTransitioningLower");
                case Light.TRANSITIONINGTOFULLOFF:
                    return Bundle.getMessage("LightStateTransitioningToFullOff");
                default:
                    return "Unexpected value: " + val;
            }
        }

        @Override
        public Object getValueAt(int row, int col) {
            switch(col) {
                case EDITCOL:
                    return Bundle.getMessage("ButtonEdit");
                case INTENSITYCOL:
                    return ((Light) getBySystemName((String) getValueAt(row, SYSNAMECOL))).getTargetIntensity();
                case ENABLECOL:
                    return ((Light) getBySystemName((String) getValueAt(row, SYSNAMECOL))).getEnabled();
                default:
                    return super.getValueAt(row, col);
            }
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            switch(col) {
                case EDITCOL:
                    // Use separate Runnable so window is created on top
                    class WindowMaker implements Runnable {

                        int row;

                        WindowMaker(int r) {
                            row = r;
                        }

                        @Override
                        public void run() {
                            // set up to edit
                            addPressed(null);
                            fixedSystemName.setText((String) getValueAt(row, SYSNAMECOL));
                            // don't really want to stop Light w/o user action
                            editPressed();
                        }
                    }
                    WindowMaker t = new WindowMaker(row);
                    javax.swing.SwingUtilities.invokeLater(t);
                    break;
                case INTENSITYCOL:
                    // alternate
                    try {
                        Light l = (Light) getBySystemName((String) getValueAt(row, SYSNAMECOL));
                        double intensity = ((Double) value);
                        if (intensity < 0) {
                            intensity = 0;
                        }
                        if (intensity > 1.0) {
                            intensity = 1.0;
                        }
                        l.setTargetIntensity(intensity);
                    } catch (IllegalArgumentException e1) {
                        status1.setText(Bundle.getMessage("LightError16"));
                    }
                    break;
                case ENABLECOL:
                    // alternate
                    Light l = (Light) getBySystemName((String) getValueAt(row, SYSNAMECOL));
                    boolean v = l.getEnabled();
                    l.setEnabled(!v);
                    break;
                case VALUECOL:
                    if (_graphicState) {
                        // respond to clicking on ImageIconRenderer CellEditor
                        Light ll = (Light) getBySystemName((String) getValueAt(row, SYSNAMECOL));
                        clickOn(ll);
                        fireTableRowsUpdated(row, row);
                        break;
                    }
                //$FALL-THROUGH$
                default:
                    super.setValueAt(value, row, col);
                    break;
            }
        }

        /**
             * Delete the bean after all the checking has been done.
             * <P>
             * Deactivate the light, then use the superclass to delete it.
             */
        @Override
        void doDelete(NamedBean bean) {
            ((Light) bean).deactivateLight();
            super.doDelete(bean);
        }

        // all properties update for now
        @Override
        protected boolean matchPropertyName(java.beans.PropertyChangeEvent e) {
            return true;
        }

        @Override
        public Manager getManager() {
            return lightManager;
        }

        @Override
        public NamedBean getBySystemName(String name) {
            return lightManager.getBySystemName(name);
        }

        @Override
        public NamedBean getByUserName(String name) {
            return lightManager.getByUserName(name);
        }

        @Override
        protected String getMasterClassName() {
            return getClassName();
        }

        @Override
        public void clickOn(NamedBean t) {
            int oldState = ((Light) t).getState();
            int newState;
            switch(oldState) {
                case Light.ON:
                    newState = Light.OFF;
                    break;
                case Light.OFF:
                    newState = Light.ON;
                    break;
                default:
                    newState = Light.OFF;
                    log.warn("Unexpected Light state " + oldState + " becomes OFF");
                    break;
            }
            ((Light) t).setState(newState);
        }

        @Override
        public JButton configureButton() {
            return new JButton(" " + Bundle.getMessage("LightStateOff") + " ");
        }

        @Override
        protected String getBeanType() {
            return Bundle.getMessage("BeanNameLight");
        }

        /**
             * Customize the light table Value (State) column to show an appropriate graphic for the light state
             * if _graphicState = true, or (default) just show the localized state text
             * when the TableDataModel is being called from ListedTableAction.
             *
             * @param table a JTable of Lights
             */
        @Override
        protected void configValueColumn(JTable table) {
            // have the value column hold a JPanel (icon)
            //setColumnToHoldButton(table, VALUECOL, new JLabel("123456")); // for small round icon, but cannot be converted to JButton
            // add extras, override BeanTableDataModel
            log.debug("Light configValueColumn (I am {})", super.toString());
            if (_graphicState) {
                // load icons, only once
                // editor
                table.setDefaultEditor(JLabel.class, new ImageIconRenderer());
                // item class copied from SwitchboardEditor panel
                table.setDefaultRenderer(JLabel.class, new ImageIconRenderer());
            } else {
                // classic text style state indication
                super.configValueColumn(table);
            }
        }

        /**
             * Visualize state in table as a graphic, customized for Lights (2 states + ... for transitioning).
             * Renderer and Editor are identical, as the cell contents are not actually edited,
             * only used to toggle state using {@link #clickOn(NamedBean)}.
             * @see jmri.jmrit.beantable.sensor.SensorTableDataModel.ImageIconRenderer
             * @see jmri.jmrit.beantable.BlockTableAction#createModel()
             * @see jmri.jmrit.beantable.TurnoutTableAction#createModel()
             */
        class ImageIconRenderer extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {

            protected JLabel label;

            // also used in display.switchboardEditor
            protected String rootPath = "resources/icons/misc/switchboard/";

            // for Light
            protected char beanTypeChar = 'L';

            protected String onIconPath = rootPath + beanTypeChar + "-on-s.png";

            protected String offIconPath = rootPath + beanTypeChar + "-off-s.png";

            protected BufferedImage onImage;

            protected BufferedImage offImage;

            protected ImageIcon onIcon;

            protected ImageIcon offIcon;

            protected int iconHeight = -1;

            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                log.debug("Renderer Item = {}, State = {}", row, value);
                if (iconHeight < 0) {
                    // load resources only first time, either for renderer or editor
                    loadIcons();
                    log.debug("icons loaded");
                }
                return updateLabel((String) value, row);
            }

            @Override
            public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
                log.debug("Renderer Item = {}, State = {}", row, value);
                if (iconHeight < 0) {
                    // load resources only first time, either for renderer or editor
                    loadIcons();
                    log.debug("icons loaded");
                }
                return updateLabel((String) value, row);
            }

            public JLabel updateLabel(String value, int row) {
                if (iconHeight > 0) {
                // if necessary, increase row height;
                //table.setRowHeight(row, Math.max(table.getRowHeight(), iconHeight - 5)); // TODO adjust table row height for Lights
                }
                if (value.equals(Bundle.getMessage("LightStateOff")) && offIcon != null) {
                    label = new JLabel(offIcon);
                    label.setVerticalAlignment(JLabel.BOTTOM);
                    log.debug("offIcon set");
                } else if (value.equals(Bundle.getMessage("LightStateOn")) && onIcon != null) {
                    label = new JLabel(onIcon);
                    label.setVerticalAlignment(JLabel.BOTTOM);
                    log.debug("onIcon set");
                } else if (value.equals(Bundle.getMessage("BeanStateInconsistent"))) {
                    // centered text alignment
                    label = new JLabel("X", JLabel.CENTER);
                    label.setForeground(Color.red);
                    log.debug("Light state inconsistent");
                    iconHeight = 0;
                } else if (value.equals(Bundle.getMessage("LightStateIntermediate"))) {
                    // centered text alignment
                    label = new JLabel("...", JLabel.CENTER);
                    log.debug("Light state in transition");
                    iconHeight = 0;
                } else {
                    // failed to load icon
                    // centered text alignment
                    label = new JLabel(value, JLabel.CENTER);
                    log.warn("Error reading icons for LightTable");
                    iconHeight = 0;
                }
                label.setToolTipText(value);
                label.addMouseListener(new MouseAdapter() {

                    @Override
                    public final void mousePressed(MouseEvent evt) {
                        log.debug("Clicked on icon in row {}", row);
                        stopCellEditing();
                    }
                });
                return label;
            }

            @Override
            public Object getCellEditorValue() {
                log.debug("getCellEditorValue, me = {})", this.toString());
                return this.toString();
            }

            /**
                 * Read and buffer graphics. Only called once for this table.
                 * @see #getTableCellEditorComponent(JTable, Object, boolean, int, int)
                 */
            protected void loadIcons() {
                try {
                    onImage = ImageIO.read(new File(onIconPath));
                    offImage = ImageIO.read(new File(offIconPath));
                } catch (IOException ex) {
                    log.error("error reading image from {} or {}", onIconPath, offIconPath, ex);
                }
                log.debug("Success reading images");
                int imageWidth = onImage.getWidth();
                int imageHeight = onImage.getHeight();
                // scale icons 50% to fit in table rows
                Image smallOnImage = onImage.getScaledInstance(imageWidth / 2, imageHeight / 2, Image.SCALE_DEFAULT);
                Image smallOffImage = offImage.getScaledInstance(imageWidth / 2, imageHeight / 2, Image.SCALE_DEFAULT);
                onIcon = new ImageIcon(smallOnImage);
                offIcon = new ImageIcon(smallOffImage);
                iconHeight = onIcon.getIconHeight();
            }
        }
    };
// end of custom data model
}
Also used : ImageIcon(javax.swing.ImageIcon) NamedBean(jmri.NamedBean) JButton(javax.swing.JButton) JTextField(javax.swing.JTextField) LightManager(jmri.LightManager) InstanceManager(jmri.InstanceManager) GuiLafPreferencesManager(apps.gui.GuiLafPreferencesManager) Manager(jmri.Manager) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) BufferedImage(java.awt.image.BufferedImage) Light(jmri.Light) AbstractCellEditor(javax.swing.AbstractCellEditor) TableCellEditor(javax.swing.table.TableCellEditor) TableCellRenderer(javax.swing.table.TableCellRenderer) MouseEvent(java.awt.event.MouseEvent) MouseAdapter(java.awt.event.MouseAdapter) JLabel(javax.swing.JLabel) IOException(java.io.IOException) JTable(javax.swing.JTable) File(java.io.File)

Example 40 with TableCellRenderer

use of javax.swing.table.TableCellRenderer in project android by JetBrains.

the class StringResourceTable method setLocaleColumnHeaderRenderers.

private void setLocaleColumnHeaderRenderers() {
    TableCellRenderer renderer = new LocaleRenderer(tableHeader.getDefaultRenderer(), (StringResourceTableModel) getModel());
    IntStream.range(FIXED_COLUMN_COUNT, getColumnCount()).mapToObj(columnModel::getColumn).forEach(column -> column.setHeaderRenderer(renderer));
}
Also used : TableCellRenderer(javax.swing.table.TableCellRenderer)

Aggregations

TableCellRenderer (javax.swing.table.TableCellRenderer)122 TableColumn (javax.swing.table.TableColumn)50 Component (java.awt.Component)47 DefaultTableCellRenderer (javax.swing.table.DefaultTableCellRenderer)24 JComponent (javax.swing.JComponent)20 JTable (javax.swing.JTable)20 TableColumnModel (javax.swing.table.TableColumnModel)18 JLabel (javax.swing.JLabel)17 JTableHeader (javax.swing.table.JTableHeader)17 MouseEvent (java.awt.event.MouseEvent)11 ColumnInfo (com.intellij.util.ui.ColumnInfo)8 ActionEvent (java.awt.event.ActionEvent)8 JButton (javax.swing.JButton)8 DefaultTableColumnModel (javax.swing.table.DefaultTableColumnModel)8 MouseAdapter (java.awt.event.MouseAdapter)7 TableCellEditor (javax.swing.table.TableCellEditor)7 TableModel (javax.swing.table.TableModel)7 ActionListener (java.awt.event.ActionListener)6 List (java.util.List)6 JPanel (javax.swing.JPanel)6