Search in sources :

Example 11 with TableCellEditor

use of javax.swing.table.TableCellEditor in project intellij-plugins by JetBrains.

the class JstdCoverageSection method removePaths.

private static void removePaths(@NotNull JBTable table) {
    int[] selected = table.getSelectedRows();
    if (selected == null || selected.length <= 0) {
        return;
    }
    if (table.isEditing()) {
        TableCellEditor editor = table.getCellEditor();
        if (editor != null) {
            editor.stopCellEditing();
        }
    }
    ExcludedTableModel model = (ExcludedTableModel) table.getModel();
    Arrays.sort(selected);
    int removedCount = 0;
    for (int indexToRemove : selected) {
        final int row = indexToRemove - removedCount;
        model.removeRow(row);
        model.fireTableRowsDeleted(row, row);
        removedCount++;
    }
    IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown(() -> {
        IdeFocusManager.getGlobalInstance().requestFocus(table, true);
    });
}
Also used : TableCellEditor(javax.swing.table.TableCellEditor)

Example 12 with TableCellEditor

use of javax.swing.table.TableCellEditor 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 13 with TableCellEditor

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

the class SignalGroupSubTableAction method setColumnToHoldButton.

/**
     * Configure colum widths for the Turnout and Sensor Conditional tables.
     *
     * @param table JTable to put button in
     * @param column index of column in table
     * @param sample sample button to use as spacer
     */
void setColumnToHoldButton(JTable table, int column, JButton sample) {
    // install a button renderer & editor
    ButtonRenderer buttonRenderer = new ButtonRenderer();
    table.setDefaultRenderer(JButton.class, buttonRenderer);
    TableCellEditor buttonEditor = new ButtonEditor(new JButton());
    table.setDefaultEditor(JButton.class, buttonEditor);
    // ensure the table rows, columns have enough room for buttons
    table.setRowHeight(sample.getPreferredSize().height);
    table.getColumnModel().getColumn(column).setPreferredWidth((sample.getPreferredSize().width) + 4);
}
Also used : ButtonEditor(jmri.util.table.ButtonEditor) JButton(javax.swing.JButton) TableCellEditor(javax.swing.table.TableCellEditor) ButtonRenderer(jmri.util.table.ButtonRenderer)

Example 14 with TableCellEditor

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

the class BlockTableAction method createModel.

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

        public static final int EDITCOL = NUMCOLUMN;

        public static final int DIRECTIONCOL = EDITCOL + 1;

        public static final int LENGTHCOL = DIRECTIONCOL + 1;

        public static final int CURVECOL = LENGTHCOL + 1;

        public static final int STATECOL = CURVECOL + 1;

        public static final int SENSORCOL = STATECOL + 1;

        public static final int REPORTERCOL = SENSORCOL + 1;

        public static final int CURRENTREPCOL = REPORTERCOL + 1;

        public static final int PERMISCOL = CURRENTREPCOL + 1;

        public static final int SPEEDCOL = PERMISCOL + 1;

        @Override
        public String getValue(String name) {
            if (name == null) {
                log.warn("requested getValue(null)");
                return "(no name)";
            }
            Block b = InstanceManager.getDefault(jmri.BlockManager.class).getBySystemName(name);
            if (b == null) {
                log.debug("requested getValue(\"" + name + "\"), Block doesn't exist");
                return "(no Block)";
            }
            Object m = b.getValue();
            if (m != null) {
                return m.toString();
            } else {
                return "";
            }
        }

        @Override
        public Manager getManager() {
            return InstanceManager.getDefault(jmri.BlockManager.class);
        }

        @Override
        public NamedBean getBySystemName(String name) {
            return InstanceManager.getDefault(jmri.BlockManager.class).getBySystemName(name);
        }

        @Override
        public NamedBean getByUserName(String name) {
            return InstanceManager.getDefault(jmri.BlockManager.class).getByUserName(name);
        }

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

        @Override
        public void clickOn(NamedBean t) {
        // don't do anything on click; not used in this class, because 
        // we override setValueAt
        }

        //Permissive and speed columns are temp disabled
        @Override
        public int getColumnCount() {
            return SPEEDCOL + 1;
        }

        @Override
        public Object getValueAt(int row, int col) {
            // some error checking
            if (row >= sysNameList.size()) {
                log.debug("requested getValueAt(\"" + row + "\"), row outside of range");
                return "Error table size";
            }
            Block b = (Block) getBySystemName(sysNameList.get(row));
            if (b == null) {
                log.debug("requested getValueAt(\"" + row + "\"), Block doesn't exist");
                return "(no Block)";
            }
            if (col == DIRECTIONCOL) {
                return jmri.Path.decodeDirection(b.getDirection());
            } else if (col == CURVECOL) {
                JComboBox<String> c = new JComboBox<String>(curveOptions);
                if (b.getCurvature() == Block.NONE) {
                    c.setSelectedItem(0);
                } else if (b.getCurvature() == Block.GRADUAL) {
                    c.setSelectedItem(gradualText);
                } else if (b.getCurvature() == Block.TIGHT) {
                    c.setSelectedItem(tightText);
                } else if (b.getCurvature() == Block.SEVERE) {
                    c.setSelectedItem(severeText);
                }
                return c;
            } else if (col == LENGTHCOL) {
                double len = 0.0;
                if (inchBox.isSelected()) {
                    len = b.getLengthIn();
                } else {
                    len = b.getLengthCm();
                }
                return (twoDigit.format(len));
            } else if (col == PERMISCOL) {
                boolean val = b.getPermissiveWorking();
                return Boolean.valueOf(val);
            } else if (col == SPEEDCOL) {
                String speed = b.getBlockSpeed();
                if (!speedList.contains(speed)) {
                    speedList.add(speed);
                }
                JComboBox<String> c = new JComboBox<String>(speedList);
                c.setEditable(true);
                c.setSelectedItem(speed);
                return c;
            } else if (col == STATECOL) {
                switch(b.getState()) {
                    case (Block.OCCUPIED):
                        return Bundle.getMessage("BlockOccupied");
                    case (Block.UNOCCUPIED):
                        return Bundle.getMessage("BlockUnOccupied");
                    case (Block.UNKNOWN):
                        return Bundle.getMessage("BlockUnknown");
                    default:
                        return Bundle.getMessage("BlockInconsistent");
                }
            } else if (col == SENSORCOL) {
                Sensor sensor = b.getSensor();
                JComboBox<String> c = new JComboBox<String>(sensorList);
                String name = "";
                if (sensor != null) {
                    name = sensor.getDisplayName();
                }
                c.setSelectedItem(name);
                return c;
            } else if (col == REPORTERCOL) {
                Reporter r = b.getReporter();
                return (r != null) ? r.getDisplayName() : null;
            } else if (col == CURRENTREPCOL) {
                return Boolean.valueOf(b.isReportingCurrent());
            } else if (col == EDITCOL) {
                //
                return Bundle.getMessage("ButtonEdit");
            } else {
                return super.getValueAt(row, col);
            }
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            // no setting of block state from table
            Block b = (Block) getBySystemName(sysNameList.get(row));
            if (col == VALUECOL) {
                b.setValue(value);
                fireTableRowsUpdated(row, row);
            } else if (col == LENGTHCOL) {
                float len = 0.0f;
                try {
                    len = jmri.util.IntlUtilities.floatValue(value.toString());
                } catch (java.text.ParseException ex2) {
                    log.error("Error parsing length value of \"{}\"", value);
                }
                if (inchBox.isSelected()) {
                    b.setLength(len * 25.4f);
                } else {
                    b.setLength(len * 10.0f);
                }
                fireTableRowsUpdated(row, row);
            } else if (col == CURVECOL) {
                @SuppressWarnings("unchecked") String cName = (String) ((JComboBox<String>) value).getSelectedItem();
                if (cName.equals(noneText)) {
                    b.setCurvature(Block.NONE);
                } else if (cName.equals(gradualText)) {
                    b.setCurvature(Block.GRADUAL);
                } else if (cName.equals(tightText)) {
                    b.setCurvature(Block.TIGHT);
                } else if (cName.equals(severeText)) {
                    b.setCurvature(Block.SEVERE);
                }
                fireTableRowsUpdated(row, row);
            } else if (col == PERMISCOL) {
                boolean boo = ((Boolean) value).booleanValue();
                b.setPermissiveWorking(boo);
                fireTableRowsUpdated(row, row);
            } else if (col == SPEEDCOL) {
                @SuppressWarnings("unchecked") String speed = (String) ((JComboBox<String>) value).getSelectedItem();
                try {
                    b.setBlockSpeed(speed);
                } catch (jmri.JmriException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage() + "\n" + speed);
                    return;
                }
                if (!speedList.contains(speed) && !speed.contains("Global")) {
                    // NOI18N
                    speedList.add(speed);
                }
                fireTableRowsUpdated(row, row);
            } else if (col == REPORTERCOL) {
                Reporter r = null;
                if (value != null && !value.equals("")) {
                    r = jmri.InstanceManager.getDefault(jmri.ReporterManager.class).provideReporter((String) value);
                }
                b.setReporter(r);
                fireTableRowsUpdated(row, row);
            } else if (col == SENSORCOL) {
                @SuppressWarnings("unchecked") String strSensor = (String) ((JComboBox<String>) value).getSelectedItem();
                b.setSensor(strSensor);
                return;
            } else if (col == CURRENTREPCOL) {
                boolean boo = ((Boolean) value).booleanValue();
                b.setReportingCurrent(boo);
                fireTableRowsUpdated(row, row);
            } else if (col == EDITCOL) {
                class WindowMaker implements Runnable {

                    Block b;

                    WindowMaker(Block b) {
                        this.b = b;
                    }

                    @Override
                    public void run() {
                        // don't really want to stop Route w/o user action
                        editButton(b);
                    }
                }
                WindowMaker t = new WindowMaker(b);
                javax.swing.SwingUtilities.invokeLater(t);
            //editButton(b);
            } else {
                super.setValueAt(value, row, col);
            }
        }

        @Override
        public String getColumnName(int col) {
            if (col == DIRECTIONCOL) {
                return Bundle.getMessage("BlockDirection");
            }
            if (col == VALUECOL) {
                return Bundle.getMessage("BlockValue");
            }
            if (col == CURVECOL) {
                return Bundle.getMessage("BlockCurveColName");
            }
            if (col == LENGTHCOL) {
                return Bundle.getMessage("BlockLengthColName");
            }
            if (col == PERMISCOL) {
                return Bundle.getMessage("BlockPermColName");
            }
            if (col == SPEEDCOL) {
                return Bundle.getMessage("BlockSpeedColName");
            }
            if (col == STATECOL) {
                return Bundle.getMessage("BlockState");
            }
            if (col == REPORTERCOL) {
                return Bundle.getMessage("BlockReporter");
            }
            if (col == SENSORCOL) {
                return Bundle.getMessage("BlockSensor");
            }
            if (col == CURRENTREPCOL) {
                return Bundle.getMessage("BlockReporterCurrent");
            }
            if (col == EDITCOL) {
                return Bundle.getMessage("ButtonEdit");
            }
            return super.getColumnName(col);
        }

        @Override
        public Class<?> getColumnClass(int col) {
            if (col == DIRECTIONCOL) {
                return String.class;
            }
            if (col == VALUECOL) {
                // not a button
                return String.class;
            }
            if (col == CURVECOL) {
                return JComboBox.class;
            }
            if (col == LENGTHCOL) {
                return String.class;
            }
            if (col == PERMISCOL) {
                return Boolean.class;
            }
            if (col == SPEEDCOL) {
                return JComboBox.class;
            }
            if (col == STATECOL) {
                if (_graphicState) {
                    // use an image to show block state
                    return JLabel.class;
                } else {
                    return String.class;
                }
            }
            if (col == REPORTERCOL) {
                return String.class;
            }
            if (col == SENSORCOL) {
                return JComboBox.class;
            }
            if (col == CURRENTREPCOL) {
                return Boolean.class;
            }
            if (col == EDITCOL) {
                return JButton.class;
            } else {
                return super.getColumnClass(col);
            }
        }

        @Override
        public int getPreferredWidth(int col) {
            if (col == DIRECTIONCOL) {
                return new JTextField(7).getPreferredSize().width;
            }
            if (col == CURVECOL) {
                return new JTextField(8).getPreferredSize().width;
            }
            if (col == LENGTHCOL) {
                return new JTextField(7).getPreferredSize().width;
            }
            if (col == PERMISCOL) {
                return new JTextField(7).getPreferredSize().width;
            }
            if (col == SPEEDCOL) {
                return new JTextField(7).getPreferredSize().width;
            }
            if (col == STATECOL) {
                return new JTextField(8).getPreferredSize().width;
            }
            if (col == REPORTERCOL) {
                return new JTextField(8).getPreferredSize().width;
            }
            if (col == SENSORCOL) {
                return new JTextField(8).getPreferredSize().width;
            }
            if (col == CURRENTREPCOL) {
                return new JTextField(7).getPreferredSize().width;
            }
            if (col == EDITCOL) {
                return new JTextField(7).getPreferredSize().width;
            } else {
                return super.getPreferredWidth(col);
            }
        }

        @Override
        public void configValueColumn(JTable table) {
        // value column isn't button, so config is null
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            if (col == CURVECOL) {
                return true;
            } else if (col == LENGTHCOL) {
                return true;
            } else if (col == PERMISCOL) {
                return true;
            } else if (col == SPEEDCOL) {
                return true;
            } else if (col == STATECOL) {
                return false;
            } else if (col == REPORTERCOL) {
                return true;
            } else if (col == SENSORCOL) {
                return true;
            } else if (col == CURRENTREPCOL) {
                return true;
            } else if (col == EDITCOL) {
                return true;
            } else {
                return super.isCellEditable(row, col);
            }
        }

        @Override
        public void configureTable(JTable table) {
            table.setDefaultRenderer(JComboBox.class, new jmri.jmrit.symbolicprog.ValueRenderer());
            table.setDefaultEditor(JComboBox.class, new jmri.jmrit.symbolicprog.ValueEditor());
            table.setDefaultRenderer(Boolean.class, new EnablingCheckboxRenderer());
            jmri.InstanceManager.sensorManagerInstance().addPropertyChangeListener(this);
            configStateColumn(table);
            super.configureTable(table);
        }

        @Override
        protected boolean matchPropertyName(java.beans.PropertyChangeEvent e) {
            return true;
        // return (e.getPropertyName().indexOf("alue")>=0);
        }

        @Override
        public JButton configureButton() {
            log.error("configureButton should not have been called");
            return null;
        }

        @Override
        public void propertyChange(java.beans.PropertyChangeEvent e) {
            if (e.getSource() instanceof jmri.SensorManager) {
                if (e.getPropertyName().equals("length") || e.getPropertyName().equals("DisplayListName")) {
                    updateSensorList();
                }
            }
            if (e.getPropertyName().equals("DefaultBlockSpeedChange")) {
                updateSpeedList();
            } else {
                super.propertyChange(e);
            }
        }

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

        @Override
        public synchronized void dispose() {
            super.dispose();
            jmri.InstanceManager.sensorManagerInstance().removePropertyChangeListener(this);
        }

        /**
             * Customize the block table State column to show an appropriate graphic for the block occupancy 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 Blocks
             */
        protected void configStateColumn(JTable table) {
            // have the state column hold a JPanel (icon)
            //setColumnToHoldButton(table, VALUECOL, new JLabel("1234")); // for small round icon, but cannot be converted to JButton
            // add extras, override BeanTableDataModel
            log.debug("Block configStateColumn (I am {})", super.toString());
            if (_graphicState) {
                // load icons, only once
                //table.setDefaultEditor(JLabel.class, new ImageIconRenderer()); // there's no editor for state column in BlockTable
                // item class copied from SwitchboardEditor panel
                table.setDefaultRenderer(JLabel.class, new ImageIconRenderer());
            // else, classic text style state indication, do nothing extra
            }
        }

        /**
             * Visualize state in table as a graphic, customized for Blocks (2 states).
             * Renderer and Editor are identical, as the cell contents are not actually edited.
             * @see jmri.jmrit.beantable.sensor.SensorTableDataModel.ImageIconRenderer
             * @see jmri.jmrit.beantable.TurnoutTableAction#createModel()
             * @see jmri.jmrit.beantable.LightTableAction#createModel()
             */
        class ImageIconRenderer extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {

            protected JLabel label;

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

            // reuse Sensor icon for block state
            protected char beanTypeChar = 'S';

            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 Block icons
                }
                if (value.equals(Bundle.getMessage("BlockUnOccupied")) && offIcon != null) {
                    label = new JLabel(offIcon);
                    label.setVerticalAlignment(JLabel.BOTTOM);
                    log.debug("offIcon set");
                } else if (value.equals(Bundle.getMessage("BlockOccupied")) && onIcon != null) {
                    label = new JLabel(onIcon);
                    label.setVerticalAlignment(JLabel.BOTTOM);
                    log.debug("onIcon set");
                } else if (value.equals(Bundle.getMessage("BlockInconsistent"))) {
                    // centered text alignment
                    label = new JLabel("X", JLabel.CENTER);
                    label.setForeground(Color.red);
                    log.debug("Block state inconsistent");
                    iconHeight = 0;
                } else if (value.equals(Bundle.getMessage("BlockUnknown"))) {
                    // centered text alignment
                    label = new JLabel("?", JLabel.CENTER);
                    log.debug("Block 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 BlockTable");
                    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) InstanceManager(jmri.InstanceManager) GuiLafPreferencesManager(apps.gui.GuiLafPreferencesManager) Manager(jmri.Manager) JTextField(javax.swing.JTextField) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) BufferedImage(java.awt.image.BufferedImage) AbstractCellEditor(javax.swing.AbstractCellEditor) TableCellEditor(javax.swing.table.TableCellEditor) TableCellRenderer(javax.swing.table.TableCellRenderer) MouseEvent(java.awt.event.MouseEvent) JComboBox(javax.swing.JComboBox) Reporter(jmri.Reporter) MouseAdapter(java.awt.event.MouseAdapter) JLabel(javax.swing.JLabel) IOException(java.io.IOException) JTable(javax.swing.JTable) Block(jmri.Block) File(java.io.File) Sensor(jmri.Sensor)

Example 15 with TableCellEditor

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

the class LogixTableAction method makeEditLogixWindow.

/**
     * Create and/or initialize the Edit Logix pane.
     */
void makeEditLogixWindow() {
    // Setup the name box components.
    setNameBoxListeners();
    //if (log.isDebugEnabled()) log.debug("makeEditLogixWindow ");
    editUserName.setText(_curLogix.getUserName());
    // clear conditional table if needed
    if (conditionalTableModel != null) {
        conditionalTableModel.fireTableStructureChanged();
    }
    inEditMode = true;
    if (editLogixFrame == null) {
        editLogixFrame = new JmriJFrame(rbx.getString("TitleEditLogix"), false, false);
        editLogixFrame.addHelpMenu("package.jmri.jmrit.beantable.LogixAddEdit", true);
        editLogixFrame.setLocation(100, 30);
        Container contentPane = editLogixFrame.getContentPane();
        contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
        JPanel panel1 = new JPanel();
        panel1.setLayout(new FlowLayout());
        JLabel systemNameLabel = new JLabel(Bundle.getMessage("ColumnSystemName") + ":");
        panel1.add(systemNameLabel);
        JLabel fixedSystemName = new JLabel(_curLogix.getSystemName());
        panel1.add(fixedSystemName);
        contentPane.add(panel1);
        JPanel panel2 = new JPanel();
        panel2.setLayout(new FlowLayout());
        JLabel userNameLabel = new JLabel(Bundle.getMessage("ColumnUserName") + ":");
        panel2.add(userNameLabel);
        panel2.add(editUserName);
        editUserName.setToolTipText(rbx.getString("LogixUserNameHint2"));
        contentPane.add(panel2);
        // add table of Conditionals
        JPanel pctSpace = new JPanel();
        pctSpace.setLayout(new FlowLayout());
        pctSpace.add(new JLabel("   "));
        contentPane.add(pctSpace);
        JPanel pTitle = new JPanel();
        pTitle.setLayout(new FlowLayout());
        pTitle.add(new JLabel(rbx.getString("ConditionalTableTitle")));
        contentPane.add(pTitle);
        // initialize table of conditionals
        conditionalTableModel = new ConditionalTableModel();
        JTable conditionalTable = new JTable(conditionalTableModel);
        conditionalTable.setRowSelectionAllowed(false);
        TableColumnModel conditionalColumnModel = conditionalTable.getColumnModel();
        TableColumn sNameColumn = conditionalColumnModel.getColumn(ConditionalTableModel.SNAME_COLUMN);
        sNameColumn.setResizable(true);
        sNameColumn.setMinWidth(100);
        sNameColumn.setPreferredWidth(130);
        TableColumn uNameColumn = conditionalColumnModel.getColumn(ConditionalTableModel.UNAME_COLUMN);
        uNameColumn.setResizable(true);
        uNameColumn.setMinWidth(210);
        uNameColumn.setPreferredWidth(260);
        TableColumn stateColumn = conditionalColumnModel.getColumn(ConditionalTableModel.STATE_COLUMN);
        stateColumn.setResizable(true);
        stateColumn.setMinWidth(50);
        stateColumn.setMaxWidth(100);
        TableColumn buttonColumn = conditionalColumnModel.getColumn(ConditionalTableModel.BUTTON_COLUMN);
        // install button renderer and editor
        ButtonRenderer buttonRenderer = new ButtonRenderer();
        conditionalTable.setDefaultRenderer(JButton.class, buttonRenderer);
        TableCellEditor buttonEditor = new ButtonEditor(new JButton());
        conditionalTable.setDefaultEditor(JButton.class, buttonEditor);
        JButton testButton = new JButton("XXXXXX");
        conditionalTable.setRowHeight(testButton.getPreferredSize().height);
        buttonColumn.setMinWidth(testButton.getPreferredSize().width);
        buttonColumn.setMaxWidth(testButton.getPreferredSize().width);
        buttonColumn.setResizable(false);
        JScrollPane conditionalTableScrollPane = new JScrollPane(conditionalTable);
        Dimension dim = conditionalTable.getPreferredSize();
        dim.height = 450;
        conditionalTableScrollPane.getViewport().setPreferredSize(dim);
        contentPane.add(conditionalTableScrollPane);
        // add message area between table and buttons
        JPanel panel4 = new JPanel();
        panel4.setLayout(new BoxLayout(panel4, BoxLayout.Y_AXIS));
        JPanel panel41 = new JPanel();
        panel41.setLayout(new FlowLayout());
        panel41.add(status);
        panel4.add(panel41);
        JPanel panel42 = new JPanel();
        panel42.setLayout(new FlowLayout());
        // Conditional panel buttons - New Conditional
        JButton newConditionalButton = new JButton(rbx.getString("NewConditionalButton"));
        panel42.add(newConditionalButton);
        newConditionalButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                newConditionalPressed(e);
            }
        });
        newConditionalButton.setToolTipText(rbx.getString("NewConditionalButtonHint"));
        // Conditional panel buttons - Reorder
        JButton reorderButton = new JButton(rbx.getString("ReorderButton"));
        panel42.add(reorderButton);
        reorderButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                reorderPressed(e);
            }
        });
        reorderButton.setToolTipText(rbx.getString("ReorderButtonHint"));
        // Conditional panel buttons - Calculate
        JButton calculateButton = new JButton(rbx.getString("CalculateButton"));
        panel42.add(calculateButton);
        calculateButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                calculatePressed(e);
            }
        });
        calculateButton.setToolTipText(rbx.getString("CalculateButtonHint"));
        panel4.add(panel42);
        Border panel4Border = BorderFactory.createEtchedBorder();
        panel4.setBorder(panel4Border);
        contentPane.add(panel4);
        // add buttons at bottom of window
        JPanel panel5 = new JPanel();
        panel5.setLayout(new FlowLayout());
        // Bottom Buttons - Done Logix
        JButton done = new JButton(Bundle.getMessage("ButtonDone"));
        panel5.add(done);
        done.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                donePressed(e);
            }
        });
        done.setToolTipText(rbx.getString("DoneButtonHint"));
        // Delete Logix
        JButton delete = new JButton(Bundle.getMessage("ButtonDelete"));
        panel5.add(delete);
        delete.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                deletePressed(e);
            }
        });
        delete.setToolTipText(rbx.getString("DeleteLogixButtonHint"));
        contentPane.add(panel5);
    }
    editLogixFrame.addWindowListener(new java.awt.event.WindowAdapter() {

        @Override
        public void windowClosing(java.awt.event.WindowEvent e) {
            if (inEditMode) {
                donePressed(null);
            } else {
                finishDone();
            }
        }
    });
    editLogixFrame.pack();
    editLogixFrame.setVisible(true);
}
Also used : JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) FlowLayout(java.awt.FlowLayout) ButtonEditor(jmri.util.table.ButtonEditor) ActionEvent(java.awt.event.ActionEvent) BoxLayout(javax.swing.BoxLayout) JButton(javax.swing.JButton) JLabel(javax.swing.JLabel) TableColumnModel(javax.swing.table.TableColumnModel) Dimension(java.awt.Dimension) TableColumn(javax.swing.table.TableColumn) Container(java.awt.Container) ActionListener(java.awt.event.ActionListener) JmriJFrame(jmri.util.JmriJFrame) JTable(javax.swing.JTable) TableCellEditor(javax.swing.table.TableCellEditor) Border(javax.swing.border.Border) ButtonRenderer(jmri.util.table.ButtonRenderer)

Aggregations

TableCellEditor (javax.swing.table.TableCellEditor)62 JButton (javax.swing.JButton)37 ButtonEditor (jmri.util.table.ButtonEditor)33 ButtonRenderer (jmri.util.table.ButtonRenderer)33 TableColumnModel (javax.swing.table.TableColumnModel)23 JLabel (javax.swing.JLabel)14 JTable (javax.swing.JTable)13 ActionEvent (java.awt.event.ActionEvent)11 ActionListener (java.awt.event.ActionListener)9 BoxLayout (javax.swing.BoxLayout)9 JPanel (javax.swing.JPanel)9 JScrollPane (javax.swing.JScrollPane)9 TableColumn (javax.swing.table.TableColumn)9 TableCellRenderer (javax.swing.table.TableCellRenderer)8 FlowLayout (java.awt.FlowLayout)6 MouseEvent (java.awt.event.MouseEvent)6 XTableColumnModel (jmri.util.swing.XTableColumnModel)6 Container (java.awt.Container)5 JTextField (javax.swing.JTextField)5 JmriJFrame (jmri.util.JmriJFrame)5