Search in sources :

Example 1 with TableSorter

use of jmri.util.com.sun.TableSorter in project JMRI by JMRI.

the class TurnoutTableAction method createModel.

/**
     * Create the JTable DataModel, along with the changes for the specific case
     * of Turnouts.
     */
@Override
protected void createModel() {
    // store the terminology
    closedText = turnManager.getClosedText();
    thrownText = turnManager.getThrownText();
    // load graphic state column display preference
    // from apps/GuiLafConfigPane.java
    _graphicState = InstanceManager.getDefault(GuiLafPreferencesManager.class).isGraphicTableState();
    // create the data model object that drives the table
    // note that this is a class creation, and very long
    m = new BeanTableDataModel() {

        @Override
        public int getColumnCount() {
            return DIVERGCOL + 1;
        }

        @Override
        public String getColumnName(int col) {
            if (col == INVERTCOL) {
                return Bundle.getMessage("Inverted");
            } else if (col == LOCKCOL) {
                return Bundle.getMessage("Locked");
            } else if (col == KNOWNCOL) {
                return Bundle.getMessage("Feedback");
            } else if (col == MODECOL) {
                return Bundle.getMessage("ModeLabel");
            } else if (col == SENSOR1COL) {
                return Bundle.getMessage("BlockSensor") + "1";
            } else if (col == SENSOR2COL) {
                return Bundle.getMessage("BlockSensor") + "2";
            } else if (col == OPSONOFFCOL) {
                return Bundle.getMessage("TurnoutAutomationMenu");
            } else if (col == OPSEDITCOL) {
                return "";
            } else if (col == LOCKOPRCOL) {
                return Bundle.getMessage("LockMode");
            } else if (col == LOCKDECCOL) {
                return Bundle.getMessage("Decoder");
            } else if (col == DIVERGCOL) {
                return Bundle.getMessage("ThrownSpeed");
            } else if (col == STRAIGHTCOL) {
                return Bundle.getMessage("ClosedSpeed");
            } else if (col == EDITCOL) {
                return "";
            } else {
                return super.getColumnName(col);
            }
        }

        @Override
        public Class<?> getColumnClass(int col) {
            if (col == INVERTCOL) {
                return Boolean.class;
            } else if (col == LOCKCOL) {
                return Boolean.class;
            } else if (col == KNOWNCOL) {
                return String.class;
            } else if (col == MODECOL) {
                return JComboBox.class;
            } else if (col == SENSOR1COL) {
                return JComboBox.class;
            } else if (col == SENSOR2COL) {
                return JComboBox.class;
            } else if (col == OPSONOFFCOL) {
                return JComboBox.class;
            } else if (col == OPSEDITCOL) {
                return JButton.class;
            } else if (col == EDITCOL) {
                return JButton.class;
            } else if (col == LOCKOPRCOL) {
                return JComboBox.class;
            } else if (col == LOCKDECCOL) {
                return JComboBox.class;
            } else if (col == DIVERGCOL) {
                return JComboBox.class;
            } else if (col == STRAIGHTCOL) {
                return JComboBox.class;
            } else if (col == VALUECOL && _graphicState) {
                // use an image to show turnout state
                return JLabel.class;
            } else {
                return super.getColumnClass(col);
            }
        }

        @Override
        public int getPreferredWidth(int col) {
            switch(col) {
                case INVERTCOL:
                    return new JTextField(6).getPreferredSize().width;
                case LOCKCOL:
                    return new JTextField(6).getPreferredSize().width;
                case LOCKOPRCOL:
                    return new JTextField(10).getPreferredSize().width;
                case LOCKDECCOL:
                    return new JTextField(10).getPreferredSize().width;
                case KNOWNCOL:
                    return new JTextField(10).getPreferredSize().width;
                case MODECOL:
                    return new JTextField(10).getPreferredSize().width;
                case SENSOR1COL:
                    return new JTextField(5).getPreferredSize().width;
                case SENSOR2COL:
                    return new JTextField(5).getPreferredSize().width;
                case OPSONOFFCOL:
                    return new JTextField(14).getPreferredSize().width;
                case OPSEDITCOL:
                    return new JTextField(7).getPreferredSize().width;
                case EDITCOL:
                    return new JTextField(7).getPreferredSize().width;
                case DIVERGCOL:
                    return new JTextField(14).getPreferredSize().width;
                case STRAIGHTCOL:
                    return new JTextField(14).getPreferredSize().width;
                default:
                    super.getPreferredWidth(col);
            }
            return super.getPreferredWidth(col);
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            String name = sysNameList.get(row);
            TurnoutManager manager = turnManager;
            Turnout t = manager.getBySystemName(name);
            if (col == INVERTCOL) {
                return t.canInvert();
            } else if (col == LOCKCOL) {
                return t.canLock(Turnout.CABLOCKOUT + Turnout.PUSHBUTTONLOCKOUT);
            } else if (col == KNOWNCOL) {
                return false;
            } else if (col == MODECOL) {
                return true;
            } else if (col == SENSOR1COL) {
                return true;
            } else if (col == SENSOR2COL) {
                return true;
            } else if (col == OPSONOFFCOL) {
                return true;
            } else if (col == OPSEDITCOL) {
                return t.getTurnoutOperation() != null;
            } else if (col == LOCKOPRCOL) {
                return true;
            } else if (col == LOCKDECCOL) {
                return true;
            } else if (col == DIVERGCOL) {
                return true;
            } else if (col == STRAIGHTCOL) {
                return true;
            } else if (col == EDITCOL) {
                return true;
            } else {
                return super.isCellEditable(row, col);
            }
        }

        @Override
        public Object getValueAt(int row, int col) {
            // some error checking
            if (row >= sysNameList.size()) {
                log.debug("row is greater than name list");
                return "error";
            }
            String name = sysNameList.get(row);
            TurnoutManager manager = turnManager;
            Turnout t = manager.getBySystemName(name);
            if (t == null) {
                log.debug("error null turnout!");
                return "error";
            }
            if (col == INVERTCOL) {
                boolean val = t.getInverted();
                return Boolean.valueOf(val);
            } else if (col == LOCKCOL) {
                boolean val = t.getLocked(Turnout.CABLOCKOUT + Turnout.PUSHBUTTONLOCKOUT);
                return Boolean.valueOf(val);
            } else if (col == KNOWNCOL) {
                if (t.getKnownState() == Turnout.CLOSED) {
                    return closedText;
                }
                if (t.getKnownState() == Turnout.THROWN) {
                    return thrownText;
                }
                if (t.getKnownState() == Turnout.INCONSISTENT) {
                    return Bundle.getMessage("BeanStateInconsistent");
                } else {
                    // "Unknown"
                    return Bundle.getMessage("BeanStateUnknown");
                }
            } else if (col == MODECOL) {
                JComboBox<String> c = new JComboBox<String>(t.getValidFeedbackNames());
                c.setSelectedItem(t.getFeedbackModeName());
                c.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        comboBoxAction(e);
                    }
                });
                return c;
            } else if (col == SENSOR1COL) {
                return t.getFirstSensor();
            } else if (col == SENSOR2COL) {
                return t.getSecondSensor();
            } else if (col == OPSONOFFCOL) {
                return makeAutomationBox(t);
            } else if (col == OPSEDITCOL) {
                return Bundle.getMessage("EditTurnoutOperation");
            } else if (col == EDITCOL) {
                return Bundle.getMessage("ButtonEdit");
            } else if (col == LOCKDECCOL) {
                JComboBox<String> c = new JComboBox<String>(t.getValidDecoderNames());
                c.setSelectedItem(t.getDecoderName());
                c.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        comboBoxAction(e);
                    }
                });
                return c;
            } else if (col == LOCKOPRCOL) {
                JComboBox<String> c = new JComboBox<String>(lockOperations);
                if (t.canLock(Turnout.CABLOCKOUT) && t.canLock(Turnout.PUSHBUTTONLOCKOUT)) {
                    c.setSelectedItem(bothText);
                } else if (t.canLock(Turnout.PUSHBUTTONLOCKOUT)) {
                    c.setSelectedItem(pushbutText);
                } else if (t.canLock(Turnout.CABLOCKOUT)) {
                    c.setSelectedItem(cabOnlyText);
                } else {
                    c.setSelectedItem(noneText);
                }
                c.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        comboBoxAction(e);
                    }
                });
                return c;
            } else if (col == STRAIGHTCOL) {
                String speed = t.getStraightSpeed();
                if (!speedListClosed.contains(speed)) {
                    speedListClosed.add(speed);
                }
                JComboBox<String> c = new JComboBox<String>(speedListClosed);
                c.setEditable(true);
                c.setSelectedItem(speed);
                return c;
            } else if (col == DIVERGCOL) {
                String speed = t.getDivergingSpeed();
                if (!speedListThrown.contains(speed)) {
                    speedListThrown.add(speed);
                }
                JComboBox<String> c = new JComboBox<String>(speedListThrown);
                c.setEditable(true);
                c.setSelectedItem(speed);
                return c;
            // } else if (col == VALUECOL && _graphicState) { // not neeeded as the
            //  graphic ImageIconRenderer uses the same super.getValueAt(row, col) as classic bean state text button
            }
            return super.getValueAt(row, col);
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            String name = sysNameList.get(row);
            TurnoutManager manager = turnManager;
            Turnout t = manager.getBySystemName(name);
            if (col == INVERTCOL) {
                if (t.canInvert()) {
                    boolean b = ((Boolean) value).booleanValue();
                    t.setInverted(b);
                }
            } else if (col == LOCKCOL) {
                boolean b = ((Boolean) value).booleanValue();
                t.setLocked(Turnout.CABLOCKOUT + Turnout.PUSHBUTTONLOCKOUT, b);
            } else if (col == MODECOL) {
                @SuppressWarnings("unchecked") String modeName = (String) ((JComboBox<String>) value).getSelectedItem();
                t.setFeedbackMode(modeName);
            } else if (col == SENSOR1COL) {
                try {
                    t.provideFirstFeedbackSensor((String) value);
                } catch (jmri.JmriException e) {
                    JOptionPane.showMessageDialog(null, e.toString());
                }
                fireTableRowsUpdated(row, row);
            } else if (col == SENSOR2COL) {
                try {
                    t.provideSecondFeedbackSensor((String) value);
                } catch (jmri.JmriException e) {
                    JOptionPane.showMessageDialog(null, e.toString());
                }
                fireTableRowsUpdated(row, row);
            } else if (col == OPSONOFFCOL) {
            // do nothing as this is handled by the combo box listener
            } else if (col == OPSEDITCOL) {
                t.setInhibitOperation(false);
                // cast to JComboBox<String> required in OPSEDITCOL
                @SuppressWarnings("unchecked") JComboBox<String> cb = (JComboBox<String>) getValueAt(row, OPSONOFFCOL);
                log.debug("opsSelected = {}", getValueAt(row, OPSONOFFCOL).toString());
                editTurnoutOperation(t, cb);
            } else if (col == EDITCOL) {
                class WindowMaker implements Runnable {

                    Turnout t;

                    WindowMaker(Turnout t) {
                        this.t = t;
                    }

                    @Override
                    public void run() {
                        editButton(t);
                    }
                }
                WindowMaker w = new WindowMaker(t);
                javax.swing.SwingUtilities.invokeLater(w);
            } else if (col == LOCKOPRCOL) {
                @SuppressWarnings("unchecked") String lockOpName = (String) ((JComboBox<String>) value).getSelectedItem();
                if (lockOpName.equals(bothText)) {
                    t.enableLockOperation(Turnout.CABLOCKOUT + Turnout.PUSHBUTTONLOCKOUT, true);
                }
                if (lockOpName.equals(cabOnlyText)) {
                    t.enableLockOperation(Turnout.CABLOCKOUT, true);
                    t.enableLockOperation(Turnout.PUSHBUTTONLOCKOUT, false);
                }
                if (lockOpName.equals(pushbutText)) {
                    t.enableLockOperation(Turnout.CABLOCKOUT, false);
                    t.enableLockOperation(Turnout.PUSHBUTTONLOCKOUT, true);
                }
            } else if (col == LOCKDECCOL) {
                @SuppressWarnings("unchecked") String decoderName = (String) ((JComboBox<String>) value).getSelectedItem();
                t.setDecoderName(decoderName);
            } else if (col == STRAIGHTCOL) {
                @SuppressWarnings("unchecked") String speed = (String) ((JComboBox<String>) value).getSelectedItem();
                try {
                    t.setStraightSpeed(speed);
                } catch (jmri.JmriException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage() + "\n" + speed);
                    return;
                }
                if ((!speedListClosed.contains(speed)) && !speed.contains("Global")) {
                    speedListClosed.add(speed);
                }
                fireTableRowsUpdated(row, row);
            } else if (col == DIVERGCOL) {
                @SuppressWarnings("unchecked") String speed = (String) ((JComboBox<String>) value).getSelectedItem();
                try {
                    t.setDivergingSpeed(speed);
                } catch (jmri.JmriException ex) {
                    JOptionPane.showMessageDialog(null, ex.getMessage() + "\n" + speed);
                    return;
                }
                if ((!speedListThrown.contains(speed)) && !speed.contains("Global")) {
                    speedListThrown.add(speed);
                }
                fireTableRowsUpdated(row, row);
            } else if (col == VALUECOL && _graphicState) {
                // respond to clicking on ImageIconRenderer CellEditor
                clickOn(t);
                fireTableRowsUpdated(row, row);
            } else {
                super.setValueAt(value, row, col);
            }
        }

        @Override
        public String getValue(String name) {
            int val = turnManager.getBySystemName(name).getCommandedState();
            switch(val) {
                case Turnout.CLOSED:
                    return closedText;
                case Turnout.THROWN:
                    return thrownText;
                case Turnout.UNKNOWN:
                    return Bundle.getMessage("BeanStateUnknown");
                case Turnout.INCONSISTENT:
                    return Bundle.getMessage("BeanStateInconsistent");
                default:
                    return "Unexpected value: " + val;
            }
        }

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

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

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

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

        @Override
        public void clickOn(NamedBean t) {
            int state = ((Turnout) t).getCommandedState();
            if (state == Turnout.CLOSED) {
                ((Turnout) t).setCommandedState(Turnout.THROWN);
            } else {
                ((Turnout) t).setCommandedState(Turnout.CLOSED);
            }
        }

        @Override
        public void configureTable(JTable tbl) {
            table = tbl;
            table.setDefaultRenderer(Boolean.class, new EnablingCheckboxRenderer());
            table.setDefaultRenderer(JComboBox.class, new jmri.jmrit.symbolicprog.ValueRenderer());
            table.setDefaultEditor(JComboBox.class, new jmri.jmrit.symbolicprog.ValueEditor());
            setColumnToHoldButton(table, OPSEDITCOL, editButton());
            setColumnToHoldButton(table, EDITCOL, editButton());
            //Hide the following columns by default
            XTableColumnModel columnModel = (XTableColumnModel) table.getColumnModel();
            TableColumn column = columnModel.getColumnByModelIndex(STRAIGHTCOL);
            columnModel.setColumnVisible(column, false);
            column = columnModel.getColumnByModelIndex(DIVERGCOL);
            columnModel.setColumnVisible(column, false);
            column = columnModel.getColumnByModelIndex(KNOWNCOL);
            columnModel.setColumnVisible(column, false);
            column = columnModel.getColumnByModelIndex(MODECOL);
            columnModel.setColumnVisible(column, false);
            column = columnModel.getColumnByModelIndex(SENSOR1COL);
            columnModel.setColumnVisible(column, false);
            column = columnModel.getColumnByModelIndex(SENSOR2COL);
            columnModel.setColumnVisible(column, false);
            column = columnModel.getColumnByModelIndex(OPSONOFFCOL);
            columnModel.setColumnVisible(column, false);
            column = columnModel.getColumnByModelIndex(OPSEDITCOL);
            columnModel.setColumnVisible(column, false);
            column = columnModel.getColumnByModelIndex(LOCKOPRCOL);
            columnModel.setColumnVisible(column, false);
            column = columnModel.getColumnByModelIndex(LOCKDECCOL);
            columnModel.setColumnVisible(column, false);
            super.configureTable(table);
        }

        // update table if turnout lock or feedback changes
        @Override
        protected boolean matchPropertyName(java.beans.PropertyChangeEvent e) {
            if (e.getPropertyName().equals("locked")) {
                return true;
            }
            if (e.getPropertyName().equals("feedbackchange")) {
                return true;
            }
            if (e.getPropertyName().equals("TurnoutDivergingSpeedChange")) {
                return true;
            }
            if (e.getPropertyName().equals("TurnoutStraightSpeedChange")) {
                return true;
            } else {
                return super.matchPropertyName(e);
            }
        }

        public void comboBoxAction(ActionEvent e) {
            if (log.isDebugEnabled()) {
                log.debug("Combobox change");
            }
            if (table != null && table.getCellEditor() != null) {
                table.getCellEditor().stopCellEditing();
            }
        }

        @Override
        public void propertyChange(java.beans.PropertyChangeEvent e) {
            if (e.getPropertyName().equals("DefaultTurnoutClosedSpeedChange")) {
                updateClosedList();
            } else if (e.getPropertyName().equals("DefaultTurnoutThrownSpeedChange")) {
                updateThrownList();
            } else {
                super.propertyChange(e);
            }
        }

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

        /**
             * Customize the turnout table Value (State) column to show an appropriate graphic for the turnout 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 Turnouts
             */
        @Override
        protected void configValueColumn(JTable table) {
            // have the value column hold a JPanel (icon)
            //setColumnToHoldButton(table, VALUECOL, new JLabel("12345678")); // for larger, wide round icon, but cannot be converted to JButton
            // add extras, override BeanTableDataModel
            log.debug("Turnout 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);
            }
        }

        @Override
        public JTable makeJTable(@Nonnull String name, @Nonnull TableModel model, @Nullable RowSorter<? extends TableModel> sorter) {
            JTable table = this.makeJTable(model);
            table.setName(name);
            table.setRowSorter(sorter);
            table.getTableHeader().setReorderingAllowed(true);
            table.setColumnModel(new XTableColumnModel());
            table.createDefaultColumnsFromModel();
            addMouseListenerToHeader(table);
            return table;
        }

        @Override
        public JTable makeJTable(TableSorter sorter) {
            JTable table = this.makeJTable((TableModel) sorter);
            table.getTableHeader().setReorderingAllowed(true);
            table.setColumnModel(new XTableColumnModel());
            table.createDefaultColumnsFromModel();
            addMouseListenerToHeader(table);
            return table;
        }

        private JTable makeJTable(TableModel model) {
            return new JTable(model) {

                @Override
                public TableCellRenderer getCellRenderer(int row, int column) {
                    // Convert the displayed index to the model index, rather than the displayed index
                    int modelColumn = this.convertColumnIndexToModel(column);
                    if (modelColumn == SENSOR1COL || modelColumn == SENSOR2COL) {
                        return getRenderer(row, modelColumn);
                    } else {
                        return super.getCellRenderer(row, column);
                    }
                }

                @Override
                public TableCellEditor getCellEditor(int row, int column) {
                    //Convert the displayed index to the model index, rather than the displayed index
                    int modelColumn = this.convertColumnIndexToModel(column);
                    if (modelColumn == SENSOR1COL || modelColumn == SENSOR2COL) {
                        return getEditor(row, modelColumn);
                    } else {
                        return super.getCellEditor(row, column);
                    }
                }

                TableCellRenderer getRenderer(int row, int column) {
                    TableCellRenderer retval = null;
                    if (column == SENSOR1COL) {
                        retval = rendererMapSensor1.get(getModel().getValueAt(row, SYSNAMECOL));
                    } else if (column == SENSOR2COL) {
                        retval = rendererMapSensor2.get(getModel().getValueAt(row, SYSNAMECOL));
                    } else {
                        return null;
                    }
                    if (retval == null) {
                        Turnout t = turnManager.getBySystemName((String) getModel().getValueAt(row, SYSNAMECOL));
                        if (t == null) {
                            return null;
                        }
                        retval = new BeanBoxRenderer();
                        if (column == SENSOR1COL) {
                            ((JmriBeanComboBox) retval).setSelectedBean(t.getFirstSensor());
                            rendererMapSensor1.put(getModel().getValueAt(row, SYSNAMECOL), retval);
                        } else {
                            ((JmriBeanComboBox) retval).setSelectedBean(t.getSecondSensor());
                            rendererMapSensor2.put(getModel().getValueAt(row, SYSNAMECOL), retval);
                        }
                    }
                    return retval;
                }

                Hashtable<Object, TableCellRenderer> rendererMapSensor1 = new Hashtable<>();

                Hashtable<Object, TableCellRenderer> rendererMapSensor2 = new Hashtable<>();

                TableCellEditor getEditor(int row, int column) {
                    TableCellEditor retval = null;
                    switch(column) {
                        case SENSOR1COL:
                            retval = editorMapSensor1.get(getModel().getValueAt(row, SYSNAMECOL));
                            break;
                        case SENSOR2COL:
                            retval = editorMapSensor2.get(getModel().getValueAt(row, SYSNAMECOL));
                            break;
                        default:
                            return null;
                    }
                    if (retval == null) {
                        Turnout t = turnManager.getBySystemName((String) getModel().getValueAt(row, SYSNAMECOL));
                        if (t == null) {
                            return null;
                        }
                        JmriBeanComboBox c;
                        if (column == SENSOR1COL) {
                            c = new JmriBeanComboBox(InstanceManager.sensorManagerInstance(), t.getFirstSensor(), JmriBeanComboBox.DisplayOptions.DISPLAYNAME);
                            retval = new BeanComboBoxEditor(c);
                            editorMapSensor1.put(getModel().getValueAt(row, SYSNAMECOL), retval);
                        } else {
                            //Must be two
                            c = new JmriBeanComboBox(InstanceManager.sensorManagerInstance(), t.getSecondSensor(), JmriBeanComboBox.DisplayOptions.DISPLAYNAME);
                            retval = new BeanComboBoxEditor(c);
                            editorMapSensor2.put(getModel().getValueAt(row, SYSNAMECOL), retval);
                        }
                        c.setFirstItemBlank(true);
                    }
                    return retval;
                }

                Hashtable<Object, TableCellEditor> editorMapSensor1 = new Hashtable<>();

                Hashtable<Object, TableCellEditor> editorMapSensor2 = new Hashtable<>();
            };
        }

        /**
             * Visualize state in table as a graphic, customized for Turnouts (4 states).
             * 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.LightTableAction#createModel()
             */
        class ImageIconRenderer extends AbstractCellEditor implements TableCellEditor, TableCellRenderer {

            protected JLabel label;

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

            // for Turnout
            protected char beanTypeChar = 'T';

            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));
                }
                if (value.equals(closedText) && offIcon != null) {
                    label = new JLabel(offIcon);
                    label.setVerticalAlignment(JLabel.BOTTOM);
                    log.debug("offIcon set");
                } else if (value.equals(thrownText) && 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("Turnout state inconsistent");
                    iconHeight = 0;
                } else if (value.equals(Bundle.getMessage("BeanStateUnknown"))) {
                    // centered text alignment
                    label = new JLabel("?", JLabel.CENTER);
                    log.debug("Turnout state unknown");
                    iconHeight = 0;
                } else {
                    // failed to load icon
                    // centered text alignment
                    label = new JLabel(value, JLabel.CENTER);
                    log.warn("Error reading icons for TurnoutTable");
                    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 : ActionEvent(java.awt.event.ActionEvent) TurnoutOperationManager(jmri.TurnoutOperationManager) InstanceManager(jmri.InstanceManager) TurnoutManager(jmri.TurnoutManager) GuiLafPreferencesManager(apps.gui.GuiLafPreferencesManager) Manager(jmri.Manager) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) JmriBeanComboBox(jmri.util.swing.JmriBeanComboBox) TableCellEditor(javax.swing.table.TableCellEditor) TableCellRenderer(javax.swing.table.TableCellRenderer) TableColumn(javax.swing.table.TableColumn) ActionListener(java.awt.event.ActionListener) JTable(javax.swing.JTable) Turnout(jmri.Turnout) File(java.io.File) TableModel(javax.swing.table.TableModel) TableSorter(jmri.util.com.sun.TableSorter) ImageIcon(javax.swing.ImageIcon) NamedBean(jmri.NamedBean) JButton(javax.swing.JButton) JTextField(javax.swing.JTextField) BufferedImage(java.awt.image.BufferedImage) AbstractCellEditor(javax.swing.AbstractCellEditor) MouseEvent(java.awt.event.MouseEvent) JComboBox(javax.swing.JComboBox) Hashtable(java.util.Hashtable) MouseAdapter(java.awt.event.MouseAdapter) JLabel(javax.swing.JLabel) IOException(java.io.IOException) XTableColumnModel(jmri.util.swing.XTableColumnModel) TurnoutManager(jmri.TurnoutManager)

Example 2 with TableSorter

use of jmri.util.com.sun.TableSorter in project JMRI by JMRI.

the class JTableUtil method sortableDataModel.

/**
     *
     * @param dataModel model for table
     * @return a table
     * @deprecated since 4.5.4; create a standard {@link javax.swing.JTable} and
     * add a {@link javax.swing.RowSorter} to that table instead. If you need
     * custom {@link javax.swing.table.TableCellEditor} selection behavior,
     * provide custom TableCellEditors for the columns that need the custom
     * behavior.
     */
@Deprecated
public static JTable sortableDataModel(TableModel dataModel) {
    TableSorter sorter;
    sorter = new TableSorter(dataModel);
    JTable dataTable = new JTable(sorter) {

        @Override
        public boolean editCellAt(int row, int column, java.util.EventObject e) {
            boolean res = super.editCellAt(row, column, e);
            java.awt.Component c = this.getEditorComponent();
            if (c instanceof javax.swing.JTextField) {
                ((JTextField) c).selectAll();
            }
            return res;
        }
    };
    sorter.setTableHeader(dataTable.getTableHeader());
    return dataTable;
}
Also used : TableSorter(jmri.util.com.sun.TableSorter) JTable(javax.swing.JTable) JTextField(javax.swing.JTextField)

Example 3 with TableSorter

use of jmri.util.com.sun.TableSorter in project JMRI by JMRI.

the class EcosLocoTableAction method createModel.

@Override
protected void createModel() {
    m = new BeanTableDataModel() {

        //We have to set a manager first off, but this gets replaced.
        @Override
        protected EcosLocoAddressManager getManager() {
            return locoManager;
        }

        protected String getRosterAttribute() {
            return rosterAttribute;
        }

        @Override
        public String getValue(String s) {
            return "Set";
        }

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

        @Override
        public void clickOn(jmri.NamedBean t) {
        }

        @Override
        protected synchronized void updateNameList() {
            // first, remove listeners from the individual objects
            if (ecosObjectIdList != null) {
                for (int i = 0; i < ecosObjectIdList.size(); i++) {
                    // if object has been deleted, it's not here; ignore it
                    jmri.jmrix.ecos.EcosLocoAddress b = getByEcosObject(ecosObjectIdList.get(i));
                    if (b != null) {
                        b.removePropertyChangeListener(this);
                    }
                }
            }
            ecosObjectIdList = getManager().getEcosObjectList();
            // and add them back in
            for (int i = 0; i < ecosObjectIdList.size(); i++) {
                getByEcosObject(ecosObjectIdList.get(i)).addPropertyChangeListener(this);
            }
        }

        @Override
        public void propertyChange(java.beans.PropertyChangeEvent e) {
            updateNameList();
            if (e.getPropertyName().equals("length")) {
                // a new jmri.jmrix.ecos.EcosLocoAddressManager is available in the manager
                updateNameList();
                fireTableDataChanged();
            } else if (matchPropertyName(e)) {
                // a value changed.  Find it, to avoid complete redraw
                String object = ((jmri.jmrix.ecos.EcosLocoAddress) e.getSource()).getEcosObject();
                // since we can add columns, the entire row is marked as updated
                int row = ecosObjectIdList.indexOf(object);
                fireTableRowsUpdated(row, row);
            }
        }

        @Override
        public int getColumnCount() {
            return STOP + 1;
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            if (col == COMMENTCOL) {
                RosterEntry re;
                String ecosObjectNo = ecosObjectIdList.get(row);
                if (value == null) {
                    return;
                } else if (value instanceof RosterEntry) {
                    re = (RosterEntry) value;
                    if ((re.getAttribute(getRosterAttribute()) != null && !re.getAttribute(getRosterAttribute()).equals(""))) {
                        JOptionPane.showMessageDialog(f, ecosObjectNo + " This roster entry already has an ECOS loco assigned to it ");
                        log.error(ecosObjectNo + " This roster entry already has an ECOS loco assigned to it ");
                        return;
                    }
                    String oldRoster = getByEcosObject(ecosObjectNo).getRosterId();
                    RosterEntry oldre;
                    if (oldRoster != null) {
                        oldre = Roster.getDefault().getEntryForId(oldRoster);
                        if (oldre != null) {
                            oldre.deleteAttribute(getRosterAttribute());
                        }
                    }
                    re.putAttribute(getRosterAttribute(), ecosObjectNo);
                    getByEcosObject(ecosObjectNo).setRosterId(re.getId());
                    re.updateFile();
                } else if (value instanceof String) {
                    List<RosterEntry> r = Roster.getDefault().getEntriesWithAttributeKeyValue(getRosterAttribute(), ecosObjectNo);
                    if (r.isEmpty()) {
                        r.get(0).deleteAttribute(getRosterAttribute());
                        getByEcosObject(ecosObjectNo).setRosterId(null);
                        r.get(0).updateFile();
                    }
                }
                Roster.getDefault().writeRoster();
            } else if (col == ADDTOROSTERCOL) {
                addToRoster(row, col);
            } else if (col == STOP) {
                stopLoco(row, col);
            } else if (col == DELETECOL) {
                // button fired, delete Bean
                deleteLoco(row, col);
            } else if (col == USERNAMECOL) {
                jmri.jmrix.ecos.EcosLocoAddress b = getByEcosObject(ecosObjectIdList.get(row));
                EcosMessage m = new EcosMessage("request(" + b.getEcosObject() + ", control, force)");
                adaptermemo.getTrafficController().sendEcosMessage(m, null);
                m = new EcosMessage("set(" + b.getEcosObject() + ", name[\"" + (String) value + "\"])");
                adaptermemo.getTrafficController().sendEcosMessage(m, null);
                m = new EcosMessage("release(" + b.getEcosObject() + ", control)");
                adaptermemo.getTrafficController().sendEcosMessage(m, null);
            }
        }

        /**
             * {@inheritDoc }
             */
        @Override
        @Deprecated
        public JTable makeJTable(TableSorter sorter) {
            return this.makeJTable((TableModel) sorter);
        }

        @Override
        public JTable makeJTable(@Nonnull String name, @Nonnull TableModel model, @Nullable RowSorter sorter) {
            JTable table = this.makeJTable(model);
            table.setName(name);
            table.setRowSorter(sorter);
            return table;
        }

        private JTable makeJTable(@Nonnull TableModel model) {
            JTable table = new JTable(model) {

                @Override
                public TableCellRenderer getCellRenderer(int row, int column) {
                    if (column == COMMENTCOL) {
                        return getRenderer(row);
                    } else {
                        return super.getCellRenderer(row, column);
                    }
                }

                @Override
                public TableCellEditor getCellEditor(int row, int column) {
                    if (column == COMMENTCOL) {
                        return getEditor(row);
                    } else {
                        return super.getCellEditor(row, column);
                    }
                }

                TableCellRenderer getRenderer(int row) {
                    TableCellRenderer retval = rendererMap.get(ecosObjectIdList.get(row));
                    if (retval == null) {
                        jmri.jmrix.ecos.EcosLocoAddress b = getByEcosObject(ecosObjectIdList.get(row));
                        RosterEntry re = null;
                        if (b != null) {
                            re = Roster.getDefault().getEntryForId(b.getRosterId());
                        }
                        retval = new RosterBoxRenderer(re);
                        rendererMap.put(ecosObjectIdList.get(row), retval);
                    }
                    return retval;
                }

                Hashtable<Object, TableCellRenderer> rendererMap = new Hashtable<>();

                TableCellEditor getEditor(int row) {
                    TableCellEditor retval = editorMap.get(ecosObjectIdList.get(row));
                    if (retval == null) {
                        jmri.jmrix.ecos.EcosLocoAddress b = getByEcosObject(ecosObjectIdList.get(row));
                        RosterEntry re = null;
                        if (b != null) {
                            re = Roster.getDefault().getEntryForId(b.getRosterId());
                        }
                        GlobalRosterEntryComboBox cb = new GlobalRosterEntryComboBox();
                        cb.setNonSelectedItem(" ");
                        if (re == null) {
                            cb.setSelectedIndex(0);
                        } else {
                            cb.setSelectedItem(re);
                        }
                        // create a new one with right aspects
                        retval = new RosterComboBoxEditor(cb);
                        editorMap.put(ecosObjectIdList.get(row), retval);
                    }
                    return retval;
                }

                Hashtable<Object, TableCellEditor> editorMap = new Hashtable<>();
            };
            table.getTableHeader().setReorderingAllowed(true);
            table.setColumnModel(new XTableColumnModel());
            table.createDefaultColumnsFromModel();
            addMouseListenerToHeader(table);
            return table;
        }

        /**
             * Is this property event announcing a change this table should
             * display?
             * <P>
             * Note that events will come both from the
             * jmri.jmrix.ecos.EcosLocoAddressManagers and also from the manager
             */
        @Override
        protected boolean matchPropertyName(java.beans.PropertyChangeEvent e) {
            if (!showLocoMonitor && (e.getPropertyName().equals("Speed") || e.getPropertyName().equals("Direction"))) {
                return false;
            }
            return true;
        }

        @Override
        public String getColumnName(int col) {
            switch(col) {
                case SYSNAMECOL:
                    return "ECoS Object Id";
                case USERNAMECOL:
                    return "ECoS Descritpion";
                case VALUECOL:
                    return "ECoS Address";
                case COMMENTCOL:
                    return "JMRI Roster Id";
                case DELETECOL:
                    return "Delete";
                case PROTOCOL:
                    return "ECOS Protocol";
                case ADDTOROSTERCOL:
                    return "Add to Roster";
                case SPEEDDIR:
                    return "Speed Direction";
                case STOP:
                    return "Stop";
                default:
                    return "unknown";
            }
        }

        @Override
        public Class<?> getColumnClass(int col) {
            switch(col) {
                case SYSNAMECOL:
                case USERNAMECOL:
                case VALUECOL:
                case PROTOCOL:
                case SPEEDDIR:
                    return String.class;
                case ADDTOROSTERCOL:
                case DELETECOL:
                case STOP:
                    return JButton.class;
                case COMMENTCOL:
                    return JComboBox.class;
                default:
                    return null;
            }
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            switch(col) {
                case COMMENTCOL:
                    return true;
                case ADDTOROSTERCOL:
                    jmri.jmrix.ecos.EcosLocoAddress b = getByEcosObject(ecosObjectIdList.get(row));
                    if (b.getRosterId() == null || b.getRosterId().equals("")) {
                        return true;
                    } else {
                        return false;
                    }
                case USERNAMECOL:
                case DELETECOL:
                case STOP:
                    return true;
                default:
                    return false;
            }
        }

        @Override
        public int getPreferredWidth(int col) {
            switch(col) {
                case SYSNAMECOL:
                    return new JTextField(5).getPreferredSize().width;
                case COMMENTCOL:
                    return new JTextField(20).getPreferredSize().width;
                case USERNAMECOL:
                    return new JTextField(20).getPreferredSize().width;
                case // not actually used due to the configureTable, setColumnToHoldButton, configureButton
                ADDTOROSTERCOL:
                    return new JTextField(12).getPreferredSize().width;
                case // not actually used due to the configureTable, setColumnToHoldButton, configureButton
                STOP:
                    return new JTextField(6).getPreferredSize().width;
                case VALUECOL:
                    return new JTextField(5).getPreferredSize().width;
                case SPEEDDIR:
                    return new JTextField(10).getPreferredSize().width;
                case PROTOCOL:
                    return new JTextField(5).getPreferredSize().width;
                default:
                    //log.warn("Unexpected column in getPreferredWidth: "+col);
                    return super.getPreferredWidth(col);
            }
        }

        @Override
        public void configureTable(JTable tbl) {
            table = tbl;
            setColumnToHoldButton(table, ADDTOROSTERCOL, new JButton("Add to Roster"));
            setColumnToHoldButton(table, STOP, stopButton());
            super.configureTable(table);
            XTableColumnModel columnModel = (XTableColumnModel) table.getColumnModel();
            TableColumn column = columnModel.getColumnByModelIndex(SPEEDDIR);
            columnModel.setColumnVisible(column, false);
            column = columnModel.getColumnByModelIndex(STOP);
            columnModel.setColumnVisible(column, false);
        }

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

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

        @Override
        public synchronized void dispose() {
            showLocoMonitor = false;
            getManager().removePropertyChangeListener(this);
            if (ecosObjectIdList != null) {
                for (int i = 0; i < ecosObjectIdList.size(); i++) {
                    jmri.jmrix.ecos.EcosLocoAddress b = getByEcosObject(ecosObjectIdList.get(i));
                    if (b != null) {
                        b.removePropertyChangeListener(this);
                    }
                }
            }
        }

        protected void deleteLoco(final int row, int col) {
            if (row >= ecosObjectIdList.size()) {
                log.debug("row is greater than list size");
                return;
            }
            jmri.jmrix.ecos.EcosLocoAddress b = getByEcosObject(ecosObjectIdList.get(row));
            final JDialog dialog = new JDialog();
            dialog.setTitle("Remove Loco From ECOS");
            dialog.setLocation(300, 200);
            dialog.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
            JPanel container = new JPanel();
            container.setLayout(new BoxLayout(container, BoxLayout.Y_AXIS));
            container.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
            JLabel question = new JLabel("Are you sure that you want to remove loco " + b.getEcosDescription() + " from the ECOS ?");
            question.setAlignmentX(Component.CENTER_ALIGNMENT);
            container.add(question);
            JButton yesButton = new JButton("Yes");
            JButton noButton = new JButton("No");
            JPanel button = new JPanel();
            button.setAlignmentX(Component.CENTER_ALIGNMENT);
            button.add(yesButton);
            button.add(noButton);
            container.add(button);
            noButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    dialog.dispose();
                }
            });
            yesButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    RemoveObjectFromEcos removeObjectFromEcos = new RemoveObjectFromEcos();
                    removeObjectFromEcos.removeObjectFromEcos(ecosObjectIdList.get(row), adaptermemo.getTrafficController());
                    dialog.dispose();
                }
            });
            container.setAlignmentX(Component.CENTER_ALIGNMENT);
            container.setAlignmentY(Component.CENTER_ALIGNMENT);
            dialog.getContentPane().add(container);
            dialog.pack();
            dialog.setModal(true);
            dialog.setVisible(true);
        }

        @Override
        public int getRowCount() {
            return ecosObjectIdList.size();
        }

        @Override
        public Object getValueAt(int row, int col) {
            if (row >= ecosObjectIdList.size()) {
                log.debug("row is greater than list size");
                return null;
            }
            jmri.jmrix.ecos.EcosLocoAddress b;
            switch(col) {
                case SYSNAMECOL:
                    return ecosObjectIdList.get(row);
                case // return user name
                USERNAMECOL:
                    // sometimes, the TableSorter invokes this on rows that no longer exist, so we check
                    b = getByEcosObject(ecosObjectIdList.get(row));
                    return (b != null) ? b.getEcosDescription() : null;
                case //
                VALUECOL:
                    b = getByEcosObject(ecosObjectIdList.get(row));
                    return (b != null) ? b.getNumber() : null;
                case COMMENTCOL:
                    b = getByEcosObject(ecosObjectIdList.get(row));
                    RosterEntry re = null;
                    if (b != null) {
                        re = Roster.getDefault().getEntryForId(b.getRosterId());
                    }
                    GlobalRosterEntryComboBox cb = (GlobalRosterEntryComboBox) table.getCellRenderer(row, col);
                    if (re == null) {
                        cb.setSelectedIndex(0);
                    } else {
                        cb.setSelectedItem(re);
                    }
                    return re;
                case PROTOCOL:
                    b = getByEcosObject(ecosObjectIdList.get(row));
                    return (b != null) ? b.getECOSProtocol() : null;
                case //
                ADDTOROSTERCOL:
                    b = getByEcosObject(ecosObjectIdList.get(row));
                    if (b.getRosterId() == null || b.getRosterId().equals("")) {
                        return "Add To Roster";
                    } else {
                        return " ";
                    }
                case STOP:
                    return "Stop";
                case SPEEDDIR:
                    b = getByEcosObject(ecosObjectIdList.get(row));
                    return (b != null) ? (b.getDirectionAsString() + " : " + b.getSpeed()) : null;
                case //
                DELETECOL:
                    return Bundle.getMessage("ButtonDelete");
                default:
                    //log.error("internal state inconsistent with table requst for "+row+" "+col);
                    return null;
            }
        }

        @Override
        protected String getBeanType() {
            return "Ecos Loco";
        }

        @Override
        protected void showPopup(MouseEvent e) {
        }
    };
}
Also used : TableSorter(jmri.util.com.sun.TableSorter) JPanel(javax.swing.JPanel) EcosMessage(jmri.jmrix.ecos.EcosMessage) NamedBean(jmri.NamedBean) ActionEvent(java.awt.event.ActionEvent) BoxLayout(javax.swing.BoxLayout) JButton(javax.swing.JButton) JTextField(javax.swing.JTextField) NamedBean(jmri.NamedBean) List(java.util.List) GlobalRosterEntryComboBox(jmri.jmrit.roster.swing.GlobalRosterEntryComboBox) TableCellEditor(javax.swing.table.TableCellEditor) TableCellRenderer(javax.swing.table.TableCellRenderer) RowSorter(javax.swing.RowSorter) TableRowSorter(javax.swing.table.TableRowSorter) MouseEvent(java.awt.event.MouseEvent) Hashtable(java.util.Hashtable) JLabel(javax.swing.JLabel) XTableColumnModel(jmri.util.swing.XTableColumnModel) TableColumn(javax.swing.table.TableColumn) EcosLocoAddressManager(jmri.jmrix.ecos.EcosLocoAddressManager) EcosLocoAddress(jmri.jmrix.ecos.EcosLocoAddress) ActionListener(java.awt.event.ActionListener) JTable(javax.swing.JTable) BeanTableDataModel(jmri.jmrit.beantable.BeanTableDataModel) RosterEntry(jmri.jmrit.roster.RosterEntry) TableModel(javax.swing.table.TableModel) JDialog(javax.swing.JDialog) RemoveObjectFromEcos(jmri.jmrix.ecos.utilities.RemoveObjectFromEcos)

Aggregations

JTable (javax.swing.JTable)3 JTextField (javax.swing.JTextField)3 TableSorter (jmri.util.com.sun.TableSorter)3 ActionEvent (java.awt.event.ActionEvent)2 ActionListener (java.awt.event.ActionListener)2 MouseEvent (java.awt.event.MouseEvent)2 Hashtable (java.util.Hashtable)2 JButton (javax.swing.JButton)2 JLabel (javax.swing.JLabel)2 TableCellEditor (javax.swing.table.TableCellEditor)2 TableCellRenderer (javax.swing.table.TableCellRenderer)2 TableColumn (javax.swing.table.TableColumn)2 TableModel (javax.swing.table.TableModel)2 NamedBean (jmri.NamedBean)2 XTableColumnModel (jmri.util.swing.XTableColumnModel)2 GuiLafPreferencesManager (apps.gui.GuiLafPreferencesManager)1 Image (java.awt.Image)1 MouseAdapter (java.awt.event.MouseAdapter)1 BufferedImage (java.awt.image.BufferedImage)1 File (java.io.File)1