Search in sources :

Example 51 with JTable

use of javax.swing.JTable in project JMRI by JMRI.

the class NodeConfigFrame method initComponents.

/**
     * Initialize the config window
     */
@Override
public void initComponents() {
    setTitle(Bundle.getMessage("WindowTitle"));
    Container contentPane = getContentPane();
    contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.Y_AXIS));
    contentPane.add(initAddressPanel());
    // Set up the pin assignment table
    assignmentPanel = new JPanel();
    assignmentPanel.setLayout(new BoxLayout(assignmentPanel, BoxLayout.Y_AXIS));
    assignmentListModel = new AssignmentTableModel();
    assignmentTable = new JTable(assignmentListModel);
    assignmentTable.setRowSelectionAllowed(false);
    assignmentTable.setPreferredScrollableViewportSize(new java.awt.Dimension(300, 350));
    JScrollPane assignmentScrollPane = new JScrollPane(assignmentTable);
    assignmentPanel.add(assignmentScrollPane, BorderLayout.CENTER);
    contentPane.add(assignmentPanel);
    contentPane.add(initNotesPanel());
    contentPane.add(initButtonPanel());
    // pack for display
    pack();
    // after the components are configured, set ourselves up as a 
    // discovery listener.
    xtc.getXBee().getNetwork().addDiscoveryListener(this);
}
Also used : JScrollPane(javax.swing.JScrollPane) JPanel(javax.swing.JPanel) Container(java.awt.Container) BoxLayout(javax.swing.BoxLayout) JTable(javax.swing.JTable)

Example 52 with JTable

use of javax.swing.JTable in project JMRI by JMRI.

the class RouteTableAction method addPressed.

@Override
protected void addPressed(ActionEvent e) {
    pref = jmri.InstanceManager.getDefault(jmri.UserPreferencesManager.class);
    if (editMode) {
        cancelEdit();
    }
    jmri.TurnoutManager tm = InstanceManager.turnoutManagerInstance();
    List<String> systemNameList = tm.getSystemNameList();
    _turnoutList = new ArrayList<>(systemNameList.size());
    Iterator<String> iter = systemNameList.iterator();
    while (iter.hasNext()) {
        String systemName = iter.next();
        String userName = tm.getBySystemName(systemName).getUserName();
        _turnoutList.add(new RouteTurnout(systemName, userName));
    }
    jmri.SensorManager sm = InstanceManager.sensorManagerInstance();
    systemNameList = sm.getSystemNameList();
    _sensorList = new ArrayList<>(systemNameList.size());
    iter = systemNameList.iterator();
    while (iter.hasNext()) {
        String systemName = iter.next();
        Sensor s = sm.getBySystemName(systemName);
        if (s != null) {
            String userName = s.getUserName();
            _sensorList.add(new RouteSensor(systemName, userName));
        } else {
            log.error("Failed to get sensor {}", systemName);
        }
    }
    initializeIncludedList();
    // Set up window
    if (addFrame == null) {
        turnoutsAlignedSensor = new JmriBeanComboBox(InstanceManager.sensorManagerInstance());
        sensor1 = new JmriBeanComboBox(InstanceManager.sensorManagerInstance());
        sensor2 = new JmriBeanComboBox(InstanceManager.sensorManagerInstance());
        sensor3 = new JmriBeanComboBox(InstanceManager.sensorManagerInstance());
        cTurnout = new JmriBeanComboBox(InstanceManager.turnoutManagerInstance());
        cLockTurnout = new JmriBeanComboBox(InstanceManager.turnoutManagerInstance());
        addFrame = new JmriJFrame(Bundle.getMessage("TitleAddRoute"), false, true);
        addFrame.addHelpMenu("package.jmri.jmrit.beantable.RouteAddEdit", true);
        addFrame.setLocation(100, 30);
        JPanel contentPanel = new JPanel();
        contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
        // add system name
        JPanel ps = new JPanel();
        ps.setLayout(new FlowLayout());
        ps.add(nameLabel);
        ps.add(_systemName);
        ps.add(_autoSystemName);
        _autoSystemName.addActionListener((ActionEvent e1) -> {
            autoSystemName();
        });
        if (pref.getSimplePreferenceState(systemNameAuto)) {
            _autoSystemName.setSelected(true);
        }
        _systemName.setToolTipText(Bundle.getMessage("TooltipRouteSystemName"));
        ps.add(fixedSystemName);
        fixedSystemName.setVisible(false);
        contentPanel.add(ps);
        // add user name
        JPanel p = new JPanel();
        p.setLayout(new FlowLayout());
        p.add(userLabel);
        p.add(_userName);
        _userName.setToolTipText(Bundle.getMessage("TooltipRouteUserName"));
        contentPanel.add(p);
        // add Turnout Display Choice
        JPanel py = new JPanel();
        py.add(new JLabel(Bundle.getMessage("Show") + ":"));
        selGroup = new ButtonGroup();
        allButton = new JRadioButton(Bundle.getMessage("All"), true);
        selGroup.add(allButton);
        py.add(allButton);
        allButton.addActionListener((ActionEvent e1) -> {
            // Setup for display of all Turnouts, if needed
            if (!showAll) {
                showAll = true;
                _routeTurnoutModel.fireTableDataChanged();
                _routeSensorModel.fireTableDataChanged();
            }
        });
        includedButton = new JRadioButton(Bundle.getMessage("Included"), false);
        selGroup.add(includedButton);
        py.add(includedButton);
        includedButton.addActionListener((ActionEvent e1) -> {
            // Setup for display of included Turnouts only, if needed
            if (showAll) {
                showAll = false;
                initializeIncludedList();
                _routeTurnoutModel.fireTableDataChanged();
                _routeSensorModel.fireTableDataChanged();
            }
        });
        py.add(new JLabel(Bundle.getMessage("_and_", Bundle.getMessage("Turnouts"), Bundle.getMessage("Sensors"))));
        // keys are in jmri.jmrit.Bundle
        contentPanel.add(py);
        // add Turnout table
        p2xt = new JPanel();
        JPanel p2xtSpace = new JPanel();
        p2xtSpace.setLayout(new BoxLayout(p2xtSpace, BoxLayout.Y_AXIS));
        p2xtSpace.add(new JLabel("XXX"));
        p2xt.add(p2xtSpace);
        JPanel p21t = new JPanel();
        p21t.setLayout(new BoxLayout(p21t, BoxLayout.Y_AXIS));
        p21t.add(new JLabel(Bundle.getMessage("SelectInRoute", Bundle.getMessage("Turnouts"))));
        p2xt.add(p21t);
        _routeTurnoutModel = new RouteTurnoutModel();
        JTable routeTurnoutTable = new JTable(_routeTurnoutModel);
        TableRowSorter<RouteTurnoutModel> rtSorter = new TableRowSorter<>(_routeTurnoutModel);
        rtSorter.setComparator(RouteTurnoutModel.SNAME_COLUMN, new SystemNameComparator());
        RowSorterUtil.setSortOrder(rtSorter, RouteTurnoutModel.SNAME_COLUMN, SortOrder.ASCENDING);
        routeTurnoutTable.setRowSorter(rtSorter);
        routeTurnoutTable.setRowSelectionAllowed(false);
        routeTurnoutTable.setPreferredScrollableViewportSize(new java.awt.Dimension(480, 80));
        ROW_HEIGHT = routeTurnoutTable.getRowHeight();
        JComboBox<String> stateTCombo = new JComboBox<>();
        stateTCombo.addItem(SET_TO_CLOSED);
        stateTCombo.addItem(SET_TO_THROWN);
        stateTCombo.addItem(SET_TO_TOGGLE);
        TableColumnModel routeTurnoutColumnModel = routeTurnoutTable.getColumnModel();
        TableColumn includeColumnT = routeTurnoutColumnModel.getColumn(RouteTurnoutModel.INCLUDE_COLUMN);
        includeColumnT.setResizable(false);
        includeColumnT.setMinWidth(50);
        includeColumnT.setMaxWidth(60);
        TableColumn sNameColumnT = routeTurnoutColumnModel.getColumn(RouteTurnoutModel.SNAME_COLUMN);
        sNameColumnT.setResizable(true);
        sNameColumnT.setMinWidth(75);
        sNameColumnT.setMaxWidth(95);
        TableColumn uNameColumnT = routeTurnoutColumnModel.getColumn(RouteTurnoutModel.UNAME_COLUMN);
        uNameColumnT.setResizable(true);
        uNameColumnT.setMinWidth(210);
        uNameColumnT.setMaxWidth(260);
        TableColumn stateColumnT = routeTurnoutColumnModel.getColumn(RouteTurnoutModel.STATE_COLUMN);
        stateColumnT.setCellEditor(new DefaultCellEditor(stateTCombo));
        stateColumnT.setResizable(false);
        stateColumnT.setMinWidth(90);
        stateColumnT.setMaxWidth(100);
        _routeTurnoutScrollPane = new JScrollPane(routeTurnoutTable);
        p2xt.add(_routeTurnoutScrollPane, BorderLayout.CENTER);
        contentPanel.add(p2xt);
        p2xt.setVisible(true);
        // add Sensor table
        p2xs = new JPanel();
        JPanel p2xsSpace = new JPanel();
        p2xsSpace.setLayout(new BoxLayout(p2xsSpace, BoxLayout.Y_AXIS));
        p2xsSpace.add(new JLabel("XXX"));
        p2xs.add(p2xsSpace);
        JPanel p21s = new JPanel();
        p21s.setLayout(new BoxLayout(p21s, BoxLayout.Y_AXIS));
        p21s.add(new JLabel(Bundle.getMessage("SelectInRoute", Bundle.getMessage("Sensors"))));
        p2xs.add(p21s);
        _routeSensorModel = new RouteSensorModel();
        JTable routeSensorTable = new JTable(_routeSensorModel);
        TableRowSorter<RouteSensorModel> rsSorter = new TableRowSorter<>(_routeSensorModel);
        rsSorter.setComparator(RouteSensorModel.SNAME_COLUMN, new SystemNameComparator());
        RowSorterUtil.setSortOrder(rsSorter, RouteSensorModel.SNAME_COLUMN, SortOrder.ASCENDING);
        routeSensorTable.setRowSorter(rsSorter);
        routeSensorTable.setRowSelectionAllowed(false);
        routeSensorTable.setPreferredScrollableViewportSize(new java.awt.Dimension(480, 80));
        JComboBox<String> stateSCombo = new JComboBox<>();
        stateSCombo.addItem(SET_TO_ACTIVE);
        stateSCombo.addItem(SET_TO_INACTIVE);
        stateSCombo.addItem(SET_TO_TOGGLE);
        TableColumnModel routeSensorColumnModel = routeSensorTable.getColumnModel();
        TableColumn includeColumnS = routeSensorColumnModel.getColumn(RouteSensorModel.INCLUDE_COLUMN);
        includeColumnS.setResizable(false);
        includeColumnS.setMinWidth(50);
        includeColumnS.setMaxWidth(60);
        TableColumn sNameColumnS = routeSensorColumnModel.getColumn(RouteSensorModel.SNAME_COLUMN);
        sNameColumnS.setResizable(true);
        sNameColumnS.setMinWidth(75);
        sNameColumnS.setMaxWidth(95);
        TableColumn uNameColumnS = routeSensorColumnModel.getColumn(RouteSensorModel.UNAME_COLUMN);
        uNameColumnS.setResizable(true);
        uNameColumnS.setMinWidth(210);
        uNameColumnS.setMaxWidth(260);
        TableColumn stateColumnS = routeSensorColumnModel.getColumn(RouteSensorModel.STATE_COLUMN);
        stateColumnS.setCellEditor(new DefaultCellEditor(stateSCombo));
        stateColumnS.setResizable(false);
        stateColumnS.setMinWidth(90);
        stateColumnS.setMaxWidth(100);
        _routeSensorScrollPane = new JScrollPane(routeSensorTable);
        p2xs.add(_routeSensorScrollPane, BorderLayout.CENTER);
        contentPanel.add(p2xs);
        p2xs.setVisible(true);
        // Enter filenames for sound, script
        JPanel p25 = new JPanel();
        p25.setLayout(new FlowLayout());
        p25.add(new JLabel(Bundle.getMessage("LabelPlaySound")));
        p25.add(soundFile);
        //NO18N
        JButton ss = new JButton("...");
        ss.addActionListener((ActionEvent e1) -> {
            setSoundPressed();
        });
        ss.setToolTipText(Bundle.getMessage("TooltipOpenFile", Bundle.getMessage("BeanNameAudio")));
        p25.add(ss);
        p25.add(new JLabel(Bundle.getMessage("LabelRunScript")));
        p25.add(scriptFile);
        //NO18N
        ss = new JButton("...");
        ss.addActionListener((ActionEvent e1) -> {
            setScriptPressed();
        });
        ss.setToolTipText(Bundle.getMessage("TooltipOpenFile", Bundle.getMessage("Script")));
        p25.add(ss);
        contentPanel.add(p25);
        //add turnouts aligned Sensor
        JPanel p27 = new JPanel();
        p27.setLayout(new FlowLayout());
        p27.add(new JLabel(Bundle.getMessage("LabelEnterSensorAligned")));
        p27.add(turnoutsAlignedSensor);
        turnoutsAlignedSensor.setFirstItemBlank(true);
        turnoutsAlignedSensor.setSelectedBean(null);
        turnoutsAlignedSensor.setToolTipText(Bundle.getMessage("TooltipEnterSensor"));
        contentPanel.add(p27);
        // add Control Sensor table
        JPanel p3 = new JPanel();
        p3.setLayout(new BoxLayout(p3, BoxLayout.Y_AXIS));
        JPanel p31 = new JPanel();
        p31.add(new JLabel(Bundle.getMessage("LabelEnterSensors")));
        p3.add(p31);
        JPanel p32 = new JPanel();
        //Sensor 1
        JPanel pS = new JPanel();
        pS.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("BeanNameSensor") + " 1"));
        pS.add(sensor1);
        pS.add(sensor1mode);
        p32.add(pS);
        //Sensor 2
        pS = new JPanel();
        pS.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("BeanNameSensor") + " 2"));
        pS.add(sensor2);
        pS.add(sensor2mode);
        p32.add(pS);
        //Sensor 3
        pS = new JPanel();
        pS.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("BeanNameSensor") + " 3"));
        pS.add(sensor3);
        pS.add(sensor3mode);
        p32.add(pS);
        sensor1.setFirstItemBlank(true);
        sensor2.setFirstItemBlank(true);
        sensor3.setFirstItemBlank(true);
        sensor1.setSelectedBean(null);
        sensor2.setSelectedBean(null);
        sensor3.setSelectedBean(null);
        String sensorHint = Bundle.getMessage("TooltipEnterSensors");
        sensor1.setToolTipText(sensorHint);
        sensor2.setToolTipText(sensorHint);
        sensor3.setToolTipText(sensorHint);
        p3.add(p32);
        // add control turnout
        JPanel p33 = new JPanel();
        p33.add(new JLabel(Bundle.getMessage("LabelEnterTurnout")));
        p3.add(p33);
        JPanel p34 = new JPanel();
        p34.add(new JLabel(Bundle.getMessage("BeanNameTurnout") + ":"));
        p34.add(cTurnout);
        cTurnout.setFirstItemBlank(true);
        cTurnout.setSelectedBean(null);
        cTurnout.setToolTipText(Bundle.getMessage("TooltipEnterTurnout"));
        p34.add(new JLabel("   " + Bundle.getMessage("LabelCondition") + ":"));
        cTurnoutStateBox.setToolTipText(Bundle.getMessage("TooltipTurnoutCondition"));
        p34.add(cTurnoutStateBox);
        p3.add(p34);
        // add added delay
        JPanel p36 = new JPanel();
        p36.add(new JLabel(Bundle.getMessage("LabelTurnoutDelay") + ":"));
        p36.add(timeDelay);
        timeDelay.setText("0");
        timeDelay.setToolTipText(Bundle.getMessage("TooltipTurnoutDelay"));
        p36.add(new JLabel(" " + Bundle.getMessage("LabelMilliseconds")));
        p3.add(p36);
        // complete this panel
        Border p3Border = BorderFactory.createEtchedBorder();
        p3.setBorder(p3Border);
        contentPanel.add(p3);
        // add lock control table
        JPanel p4 = new JPanel();
        p4.setLayout(new BoxLayout(p4, BoxLayout.Y_AXIS));
        // add lock control turnout
        JPanel p43 = new JPanel();
        p43.add(new JLabel(Bundle.getMessage("LabelLockTurnout")));
        p4.add(p43);
        JPanel p44 = new JPanel();
        p44.add(new JLabel(Bundle.getMessage("BeanNameTurnout") + ":"));
        p44.add(cLockTurnout);
        cLockTurnout.setFirstItemBlank(true);
        cLockTurnout.setSelectedBean(null);
        cLockTurnout.setToolTipText(Bundle.getMessage("TooltipEnterTurnout"));
        p44.add(new JLabel("   " + Bundle.getMessage("LabelCondition") + ":"));
        cLockTurnoutStateBox.setToolTipText(Bundle.getMessage("TooltipLockTurnout"));
        p44.add(cLockTurnoutStateBox);
        p4.add(p44);
        // complete this panel
        Border p4Border = BorderFactory.createEtchedBorder();
        p4.setBorder(p4Border);
        contentPanel.add(p4);
        // add notes panel
        JPanel pa = new JPanel();
        pa.setLayout(new BoxLayout(pa, BoxLayout.Y_AXIS));
        JPanel p1 = new JPanel();
        p1.setLayout(new FlowLayout());
        p1.add(status1);
        JPanel p2 = new JPanel();
        p2.setLayout(new FlowLayout());
        p2.add(status2);
        pa.add(p1);
        pa.add(p2);
        Border pBorder = BorderFactory.createEtchedBorder();
        pa.setBorder(pBorder);
        contentPanel.add(pa);
        // add Buttons panel
        JPanel pb = new JPanel();
        pb.setLayout(new FlowLayout(FlowLayout.TRAILING));
        // Cancel (Add) button
        pb.add(cancelButton);
        cancelButton.addActionListener(this::cancelAddPressed);
        // CancelEdit button
        pb.add(cancelEditButton);
        cancelEditButton.addActionListener(this::cancelPressed);
        cancelEditButton.setToolTipText(Bundle.getMessage("TooltipCancelRoute"));
        // Add Create Route button
        pb.add(createButton);
        createButton.addActionListener(this::createPressed);
        createButton.setToolTipText(Bundle.getMessage("TooltipCreateRoute"));
        // Edit Route button 
        pb.add(editButton);
        editButton.addActionListener(this::editPressed);
        editButton.setToolTipText(Bundle.getMessage("TooltipEditRoute"));
        // Delete Route button
        pb.add(deleteButton);
        deleteButton.addActionListener(this::deletePressed);
        deleteButton.setToolTipText(Bundle.getMessage("TooltipDeleteRoute"));
        // Update Route button
        pb.add(updateButton);
        updateButton.addActionListener((ActionEvent e1) -> {
            updatePressed(e1, false);
        });
        updateButton.setToolTipText(Bundle.getMessage("TooltipUpdateRoute"));
        // Export button
        pb.add(exportButton);
        exportButton.addActionListener(this::exportPressed);
        exportButton.setToolTipText(Bundle.getMessage("TooltipExportRoute"));
        // Show the initial buttons, and hide the others
        exportButton.setVisible(false);
        // show CancelAdd button
        cancelButton.setVisible(true);
        cancelEditButton.setVisible(false);
        updateButton.setVisible(true);
        editButton.setVisible(true);
        createButton.setVisible(true);
        deleteButton.setVisible(false);
        contentPanel.add(pb);
        addFrame.getContentPane().add(new JScrollPane(contentPanel), BorderLayout.CENTER);
        // pack and release space
        addFrame.pack();
        p2xsSpace.setVisible(false);
        p2xtSpace.setVisible(false);
    }
    // set listener for window closing
    addFrame.addWindowListener(new java.awt.event.WindowAdapter() {

        @Override
        public void windowClosing(java.awt.event.WindowEvent e) {
            // remind to save, if Route was created or edited
            if (routeDirty) {
                InstanceManager.getDefault(jmri.UserPreferencesManager.class).showInfoMessage(Bundle.getMessage("ReminderTitle"), Bundle.getMessage("ReminderSaveString", Bundle.getMessage("MenuItemRouteTable")), getClassName(), //NOI18N
                "remindSaveRoute");
                routeDirty = false;
            }
            // hide addFrame
            if (addFrame != null) {
                addFrame.setVisible(false);
            // addFrame.dispose(); // causes multiple empty Routes next time
            }
            // if in Edit, cancel edit mode
            if (editMode) {
                cancelEdit();
            }
            _routeSensorModel.dispose();
            _routeTurnoutModel.dispose();
        }
    });
    // display the window
    addFrame.setVisible(true);
    autoSystemName();
}
Also used : JPanel(javax.swing.JPanel) FlowLayout(java.awt.FlowLayout) JRadioButton(javax.swing.JRadioButton) ActionEvent(java.awt.event.ActionEvent) BoxLayout(javax.swing.BoxLayout) JButton(javax.swing.JButton) TableColumnModel(javax.swing.table.TableColumnModel) JmriBeanComboBox(jmri.util.swing.JmriBeanComboBox) TableRowSorter(javax.swing.table.TableRowSorter) JScrollPane(javax.swing.JScrollPane) JComboBox(javax.swing.JComboBox) JLabel(javax.swing.JLabel) TableColumn(javax.swing.table.TableColumn) DefaultCellEditor(javax.swing.DefaultCellEditor) JmriJFrame(jmri.util.JmriJFrame) ButtonGroup(javax.swing.ButtonGroup) JTable(javax.swing.JTable) SystemNameComparator(jmri.util.SystemNameComparator) Border(javax.swing.border.Border) Sensor(jmri.Sensor)

Example 53 with JTable

use of javax.swing.JTable in project JMRI by JMRI.

the class RouteTableAction method createModel.

/**
     * Create the JTable DataModel, along with the changes for the specific case
     * of Routes
     */
@Override
protected void createModel() {
    // late initialization of string "constants" so that TurnoutManager 
    // has time to be fully configured
    SET_TO_CLOSED = Bundle.getMessage("Set") + " " + InstanceManager.turnoutManagerInstance().getClosedText();
    SET_TO_THROWN = Bundle.getMessage("Set") + " " + InstanceManager.turnoutManagerInstance().getThrownText();
    turnoutInputModes = new String[] { Bundle.getMessage("OnCondition") + " " + InstanceManager.turnoutManagerInstance().getClosedText(), Bundle.getMessage("OnCondition") + " " + InstanceManager.turnoutManagerInstance().getThrownText(), Bundle.getMessage("OnConditionChange"), "Veto " + Bundle.getMessage("WhenCondition") + " " + Bundle.getMessage("TurnoutStateClosed"), "Veto " + Bundle.getMessage("WhenCondition") + " " + Bundle.getMessage("TurnoutStateThrown") };
    lockTurnoutInputModes = new String[] { Bundle.getMessage("OnCondition") + " " + InstanceManager.turnoutManagerInstance().getClosedText(), Bundle.getMessage("OnCondition") + " " + InstanceManager.turnoutManagerInstance().getThrownText(), Bundle.getMessage("OnConditionChange") };
    m = new BeanTableDataModel() {

        public static final int ENABLECOL = NUMCOLUMN;

        public static final int LOCKCOL = ENABLECOL + 1;

        public static final int SETCOL = ENABLECOL + 2;

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

        @Override
        public String getColumnName(int col) {
            if (col == VALUECOL) {
                // no heading on "Set"
                return "";
            }
            if (col == SETCOL) {
                // no heading on "Edit"
                return "";
            }
            if (col == ENABLECOL) {
                return Bundle.getMessage("ColumnHeadEnabled");
            }
            if (col == LOCKCOL) {
                return Bundle.getMessage("Locked");
            } else {
                return super.getColumnName(col);
            }
        }

        @Override
        public Class<?> getColumnClass(int col) {
            if (col == SETCOL) {
                return JButton.class;
            }
            if (col == ENABLECOL) {
                return Boolean.class;
            }
            if (col == LOCKCOL) {
                return Boolean.class;
            } else {
                return super.getColumnClass(col);
            }
        }

        @Override
        public int getPreferredWidth(int col) {
            if (col == SETCOL) {
                return new JTextField(6).getPreferredSize().width;
            }
            if (col == ENABLECOL) {
                return new JTextField(6).getPreferredSize().width;
            }
            if (col == LOCKCOL) {
                return new JTextField(6).getPreferredSize().width;
            } else {
                return super.getPreferredWidth(col);
            }
        }

        @Override
        public boolean isCellEditable(int row, int col) {
            if (col == USERNAMECOL) {
                return true;
            }
            if (col == SETCOL) {
                return true;
            }
            if (col == ENABLECOL) {
                return true;
            }
            // Route lock is available if turnouts are lockable
            if (col == LOCKCOL) {
                Route r = (Route) getBySystemName((String) getValueAt(row, SYSNAMECOL));
                return r.canLock();
            } else {
                return super.isCellEditable(row, col);
            }
        }

        @Override
        public Object getValueAt(int row, int col) {
            switch(col) {
                case SETCOL:
                    return Bundle.getMessage("ButtonEdit");
                case ENABLECOL:
                    return ((Route) getBySystemName((String) getValueAt(row, SYSNAMECOL))).getEnabled();
                case LOCKCOL:
                    Route r = (Route) getBySystemName((String) getValueAt(row, SYSNAMECOL));
                    if (r.canLock()) {
                        return ((Route) getBySystemName((String) getValueAt(row, SYSNAMECOL))).getLocked();
                    } else {
                        // this covers the case when route was locked and lockable turnouts were removed from the route
                        r.setLocked(false);
                        return false;
                    }
                default:
                    return super.getValueAt(row, col);
            }
        }

        @Override
        public void setValueAt(Object value, int row, int col) {
            switch(col) {
                case USERNAMECOL:
                    // check to see if user name already exists
                    if (((String) value).equals("")) {
                        value = null;
                    } else {
                        NamedBean nB = getByUserName((String) value);
                        if (nB != null) {
                            log.error("User Name is not unique " + value);
                            String msg;
                            msg = Bundle.getMessage("WarningUserName", new Object[] { ("" + value) });
                            JOptionPane.showMessageDialog(null, msg, Bundle.getMessage("WarningTitle"), JOptionPane.ERROR_MESSAGE);
                            return;
                        }
                    }
                    NamedBean nBean = getBySystemName(sysNameList.get(row));
                    nBean.setUserName((String) value);
                    fireTableRowsUpdated(row, row);
                    break;
                case SETCOL:
                    // set up to edit. Use separate Runnable so window is created on top
                    class WindowMaker implements Runnable {

                        int row;

                        WindowMaker(int r) {
                            row = r;
                        }

                        @Override
                        public void run() {
                            addPressed(null);
                            _systemName.setText((String) getValueAt(row, SYSNAMECOL));
                            // don't really want to stop Route w/o user action
                            editPressed(null);
                        }
                    }
                    WindowMaker t = new WindowMaker(row);
                    javax.swing.SwingUtilities.invokeLater(t);
                    break;
                case ENABLECOL:
                    {
                        // alternate
                        Route r = (Route) getBySystemName((String) getValueAt(row, SYSNAMECOL));
                        boolean v = r.getEnabled();
                        r.setEnabled(!v);
                        break;
                    }
                case LOCKCOL:
                    {
                        // alternate
                        Route r = (Route) getBySystemName((String) getValueAt(row, SYSNAMECOL));
                        boolean v = r.getLocked();
                        r.setLocked(!v);
                        break;
                    }
                default:
                    super.setValueAt(value, row, col);
                    break;
            }
        }

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

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

        // want to update when enabled parameter changes
        @Override
        protected boolean matchPropertyName(java.beans.PropertyChangeEvent e) {
            if (e.getPropertyName().equals("Enabled")) {
                //NOI18N
                return true;
            }
            if (e.getPropertyName().equals("Locked")) {
                //NOI18N
                return true;
            } else {
                return super.matchPropertyName(e);
            }
        }

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

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

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

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

        @Override
        public void clickOn(NamedBean t) {
            ((Route) t).setRoute();
        }

        @Override
        public String getValue(String s) {
            return Bundle.getMessage("Set");
        //Title of Set button in Route table
        }

        //public JButton configureButton() {
        //    return new JButton("Foo"));
        //not used
        //}
        @Override
        protected String getBeanType() {
            return Bundle.getMessage("BeanNameRoute");
        }

        /*Routes do not get references by other parts of the code, we therefore 
             do not need to worry about controlling how the username is changed
             */
        @Override
        protected void showPopup(MouseEvent e) {
        }
    };
}
Also used : MouseEvent(java.awt.event.MouseEvent) NamedBean(jmri.NamedBean) JComboBox(javax.swing.JComboBox) JTextField(javax.swing.JTextField) InstanceManager(jmri.InstanceManager) Manager(jmri.Manager) JTable(javax.swing.JTable) Route(jmri.Route)

Example 54 with JTable

use of javax.swing.JTable in project JMRI by JMRI.

the class RowComboBoxPanel method isCellEditable.

/**
     *  Is the cell editable? If the mouse was pressed at a margin
     *  we don't want the cell to be editable.
     *
     *  @param evt The event-object
     *  @return true when user clicked inside cell, not on cell border
     */
@Override
public boolean isCellEditable(EventObject evt) {
    this.startEditingEvent = evt;
    if (evt instanceof MouseEvent && evt.getSource() instanceof JTable) {
        MouseEvent me = (MouseEvent) evt;
        JTable table = (JTable) me.getSource();
        Point pt = new Point(me.getX(), me.getY());
        int row = table.rowAtPoint(pt);
        int col = table.columnAtPoint(pt);
        Rectangle rec = table.getCellRect(row, col, false);
        if (me.getY() >= rec.y + rec.height || me.getX() >= rec.x + rec.width) {
            return false;
        }
    }
    return super.isCellEditable(evt);
}
Also used : MouseEvent(java.awt.event.MouseEvent) JTable(javax.swing.JTable) Rectangle(java.awt.Rectangle) Point(java.awt.Point) Point(java.awt.Point)

Example 55 with JTable

use of javax.swing.JTable 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)

Aggregations

JTable (javax.swing.JTable)584 JScrollPane (javax.swing.JScrollPane)282 JPanel (javax.swing.JPanel)217 Dimension (java.awt.Dimension)145 JButton (javax.swing.JButton)139 BorderLayout (java.awt.BorderLayout)133 JLabel (javax.swing.JLabel)129 ActionEvent (java.awt.event.ActionEvent)109 ActionListener (java.awt.event.ActionListener)81 TableColumn (javax.swing.table.TableColumn)79 DefaultTableModel (javax.swing.table.DefaultTableModel)75 Component (java.awt.Component)66 BoxLayout (javax.swing.BoxLayout)66 FlowLayout (java.awt.FlowLayout)58 MouseEvent (java.awt.event.MouseEvent)58 JTextField (javax.swing.JTextField)57 TableColumnModel (javax.swing.table.TableColumnModel)52 GridBagConstraints (java.awt.GridBagConstraints)46 TableCellRenderer (javax.swing.table.TableCellRenderer)43 Test (org.junit.Test)43