예제 #1
0
 public RoutesTableModel() {
   super();
   manager = RouteManager.instance();
   manager.addPropertyChangeListener(this);
   LocationManager.instance().addPropertyChangeListener(this);
   updateList();
 }
예제 #2
0
 public void dispose() {
   if (log.isDebugEnabled()) {
     log.debug("dispose");
   }
   if (ref != null) {
     ref.dispose();
   }
   manager.removePropertyChangeListener(this);
   LocationManager.instance().removePropertyChangeListener(this);
   removePropertyChangeRoutes();
 }
예제 #3
0
 public void propertyChange(java.beans.PropertyChangeEvent e) {
   if (Control.showProperty) {
     log.debug(
         "Property change: ({}) old: ({}) new: ({})",
         e.getPropertyName(),
         e.getOldValue(),
         e.getNewValue());
   }
   if (e.getPropertyName().equals(CarRoads.CARROADS_CHANGED_PROPERTY)) {
     CarRoads.instance().updateComboBox(roadComboBox);
     if (_engine != null) {
       roadComboBox.setSelectedItem(_engine.getRoadName());
     }
   }
   if (e.getPropertyName().equals(EngineModels.ENGINEMODELS_CHANGED_PROPERTY)) {
     engineModels.updateComboBox(modelComboBox);
     if (_engine != null) {
       modelComboBox.setSelectedItem(_engine.getModel());
     }
   }
   if (e.getPropertyName().equals(EngineTypes.ENGINETYPES_CHANGED_PROPERTY)) {
     engineTypes.updateComboBox(typeComboBox);
     if (_engine != null) {
       typeComboBox.setSelectedItem(_engine.getTypeName());
     }
   }
   if (e.getPropertyName().equals(EngineLengths.ENGINELENGTHS_CHANGED_PROPERTY)) {
     engineLengths.updateComboBox(lengthComboBox);
     if (_engine != null) {
       lengthComboBox.setSelectedItem(_engine.getLength());
     }
   }
   if (e.getPropertyName().equals(EngineManager.CONSISTLISTLENGTH_CHANGED_PROPERTY)) {
     manager.updateConsistComboBox(consistComboBox);
     if (_engine != null) {
       consistComboBox.setSelectedItem(_engine.getConsistName());
     }
   }
   if (e.getPropertyName().equals(CarOwners.CAROWNERS_CHANGED_PROPERTY)) {
     CarOwners.instance().updateComboBox(ownerComboBox);
     if (_engine != null) {
       ownerComboBox.setSelectedItem(_engine.getOwner());
     }
   }
   if (e.getPropertyName().equals(LocationManager.LISTLENGTH_CHANGED_PROPERTY)) {
     LocationManager.instance().updateComboBox(locationBox);
     if (_engine != null) {
       locationBox.setSelectedItem(_engine.getLocation());
     }
   }
   if (e.getPropertyName().equals(EngineAttributeEditFrame.DISPOSE)) {
     editActive = false;
   }
 }
 @Override
 public void doAction() {
   if (getAutomationItem() != null) {
     boolean isChanged = true;
     if (!Setup.isGenerateCsvSwitchListEnabled()) {
       log.warn("Generate CSV Switch List isn't enabled!");
       finishAction(false);
       return;
     }
     // we do need one of these!
     if (!TrainCustomSwitchList.manifestCreatorFileExists()) {
       log.warn(
           "Manifest creator file not found!, directory name: {}, file name: {}",
           TrainCustomSwitchList.getDirectoryName(),
           TrainCustomSwitchList.getFileName());
       finishAction(false);
       return;
     }
     setRunning(true);
     TrainSwitchLists trainSwitchLists = new TrainSwitchLists();
     TrainCsvSwitchLists trainCsvSwitchLists = new TrainCsvSwitchLists();
     for (Location location : LocationManager.instance().getLocationsByNameList()) {
       if (location.isSwitchListEnabled()
           && (!isChanged || isChanged && location.getStatus().equals(Location.MODIFIED))) {
         // also build the regular switch lists so they can be used
         if (!Setup.isSwitchListRealTime()) {
           trainSwitchLists.buildSwitchList(location);
         }
         File csvFile = trainCsvSwitchLists.buildSwitchList(location);
         if (csvFile == null || !csvFile.exists()) {
           log.error("CSV switch list file was not created for location {}", location.getName());
           finishAction(false);
           return;
         }
         TrainCustomSwitchList.addCVSFile(csvFile);
       }
     }
     // Processes the CSV Manifest files using an external custom program.
     int fileCount = TrainCustomSwitchList.getFileCount();
     boolean status = TrainCustomSwitchList.process();
     if (status) {
       try {
         TrainCustomSwitchList.waitForProcessToComplete(
             Control.excelWaitTime * fileCount); // wait up to 60 seconds per file
       } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
     }
     // set trains switch lists printed
     TrainManager.instance().setTrainsSwitchListStatus(Train.PRINTED);
     finishAction(status);
   }
 }
예제 #5
0
 public void buildSwitchLists() {
   TrainSwitchLists trainSwitchLists = new TrainSwitchLists();
   String locationName = ""; // only create switch lists once for locations with similar names
   for (Location location : LocationManager.instance().getLocationsByNameList()) {
     if (location.isSwitchListEnabled()
         && !locationName.equals(TrainCommon.splitString(location.getName()))) {
       trainSwitchLists.buildSwitchList(location);
       // print switch lists for locations that have changes
       if (Setup.isSwitchListRealTime() && location.getStatus().equals(Location.MODIFIED)) {
         trainSwitchLists.printSwitchList(
             location, TrainManager.instance().isPrintPreviewEnabled());
         locationName = TrainCommon.splitString(location.getName());
       }
     }
   }
   // set trains switch lists printed
   TrainManager.instance().setTrainsSwitchListStatus(Train.PRINTED);
 }
/**
 * Frame for adding and editing train schedules (Timetable) for operations.
 *
 * @author Bob Jacobsen Copyright (C) 2001
 * @author Daniel Boudreau Copyright (C) 2010, 2012
 * @version $Revision$
 */
public class TrainsScheduleTableFrame extends OperationsFrame implements PropertyChangeListener {

  // public static SwingShutDownTask trainDirtyTask;

  public static final String NAME = Bundle.getMessage("Name"); // Sort by choices
  public static final String TIME = Bundle.getMessage("Time");

  TrainManager trainManager = TrainManager.instance();
  TrainScheduleManager trainScheduleManager = TrainScheduleManager.instance();
  LocationManager locationManager = LocationManager.instance();

  TrainsScheduleTableModel trainsScheduleModel = new TrainsScheduleTableModel();
  javax.swing.JTable trainsScheduleTable = new javax.swing.JTable(trainsScheduleModel);
  JScrollPane trainsPane;

  // labels
  JLabel textSort = new JLabel(Bundle.getMessage("SortBy"));

  // radio buttons
  JRadioButton sortByName = new JRadioButton(NAME);
  JRadioButton sortByTime = new JRadioButton(TIME);

  JRadioButton noneButton = new JRadioButton(Bundle.getMessage("None"));

  // radio button groups
  ButtonGroup schGroup = new ButtonGroup();

  // major buttons
  JButton selectButton = new JButton(Bundle.getMessage("Select"));
  JButton clearButton = new JButton(Bundle.getMessage("Clear"));

  JButton applyButton = new JButton(Bundle.getMessage("Apply"));
  JButton buildButton = new JButton(Bundle.getMessage("Build"));
  JButton printButton = new JButton(Bundle.getMessage("Print"));
  JButton switchListsButton = new JButton();
  JButton terminateButton = new JButton(Bundle.getMessage("Terminate"));

  JButton activateButton = new JButton(Bundle.getMessage("Activate"));
  JButton saveButton = new JButton(Bundle.getMessage("Save"));

  // check boxes
  // panel
  JPanel schedule = new JPanel();

  // text area
  JTextArea commentTextArea = new JTextArea(2, 70);
  JScrollPane commentScroller =
      new JScrollPane(
          commentTextArea,
          JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
          JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

  public TrainsScheduleTableFrame() {

    // general GUI configuration
    getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

    // Set up the jtable in a Scroll Pane..
    trainsPane = new JScrollPane(trainsScheduleTable);
    trainsPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
    trainsPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    trainsScheduleModel.initTable(trainsScheduleTable, this);

    // row comment
    JPanel pC = new JPanel();
    pC.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Comment")));
    pC.setLayout(new GridBagLayout());
    addItem(pC, commentScroller, 1, 0);

    // adjust text area width based on window size
    adjustTextAreaColumnWidth(commentScroller, commentTextArea);

    // Set up the control panel
    // row 1
    JPanel cp1 = new JPanel();
    cp1.setLayout(new BoxLayout(cp1, BoxLayout.X_AXIS));

    // row 1
    JPanel sortBy = new JPanel();
    sortBy.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("SortBy")));
    sortBy.add(sortByTime);
    sortBy.add(sortByName);

    // row 2
    schedule.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Active")));
    updateControlPanel();

    cp1.add(sortBy);
    cp1.add(schedule);

    JPanel pButtons = new JPanel();
    pButtons.setLayout(new BoxLayout(pButtons, BoxLayout.X_AXIS));

    JPanel cp3 = new JPanel();
    cp3.setBorder(BorderFactory.createTitledBorder(""));
    cp3.add(clearButton);
    cp3.add(selectButton);

    JPanel cp4 = new JPanel();
    cp4.setBorder(BorderFactory.createTitledBorder(""));
    cp4.add(applyButton);
    cp4.add(buildButton);
    cp4.add(printButton);
    cp4.add(switchListsButton);
    cp4.add(terminateButton);

    JPanel cp5 = new JPanel();
    cp5.setBorder(BorderFactory.createTitledBorder(""));
    cp5.add(activateButton);
    cp5.add(saveButton);

    pButtons.add(cp3);
    pButtons.add(cp4);
    pButtons.add(cp5);

    // tool tips
    selectButton.setToolTipText(Bundle.getMessage("SelectAllButtonTip"));
    clearButton.setToolTipText(Bundle.getMessage("ClearAllButtonTip"));
    applyButton.setToolTipText(Bundle.getMessage("ApplyButtonTip"));
    buildButton.setToolTipText(Bundle.getMessage("BuildSelectedTip"));
    activateButton.setToolTipText(Bundle.getMessage("ActivateButtonTip"));
    terminateButton.setToolTipText(Bundle.getMessage("TerminateSelectedTip"));

    setPrintButtonText();
    setSwitchListButtonText();

    // place controls in scroll pane
    JPanel controlPanel = new JPanel();
    controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
    controlPanel.add(pC);
    controlPanel.add(cp1);
    controlPanel.add(pButtons);

    JScrollPane controlPane = new JScrollPane(controlPanel);
    // make sure control panel is the right size
    controlPane.setMinimumSize(new Dimension(500, 480));
    controlPane.setMaximumSize(new Dimension(2000, 500));
    controlPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER);

    getContentPane().add(trainsPane);
    getContentPane().add(controlPane);

    // setup buttons
    addButtonAction(clearButton);
    addButtonAction(selectButton);
    addButtonAction(applyButton);
    addButtonAction(buildButton);
    addButtonAction(printButton);
    addButtonAction(switchListsButton);
    addButtonAction(terminateButton);
    addButtonAction(activateButton);
    addButtonAction(saveButton);

    ButtonGroup sortGroup = new ButtonGroup();
    sortGroup.add(sortByTime);
    sortGroup.add(sortByName);
    sortByTime.setSelected(true);

    addRadioButtonAction(sortByTime);
    addRadioButtonAction(sortByName);

    addRadioButtonAction(noneButton);

    // build menu
    JMenuBar menuBar = new JMenuBar();
    JMenu toolMenu = new JMenu(Bundle.getMessage("Tools"));
    toolMenu.add(new TrainsScheduleEditAction());
    menuBar.add(toolMenu);
    setJMenuBar(menuBar);

    // add help menu to window
    addHelpMenu("package.jmri.jmrit.operations.Operations_Timetable", true); // NOI18N

    setTitle(Bundle.getMessage("TitleTimeTableTrains"));

    initMinimumSize(new Dimension(Control.panelWidth700, Control.panelHeight500));

    addHorizontalScrollBarKludgeFix(controlPane, controlPanel);

    Setup.addPropertyChangeListener(this);
    trainManager.addPropertyChangeListener(this);
    trainScheduleManager.addPropertyChangeListener(this);
    addPropertyChangeLocations();
    addPropertyChangeTrainSchedules();
  }

  public void radioButtonActionPerformed(java.awt.event.ActionEvent ae) {
    log.debug("radio button activated");
    if (ae.getSource() == sortByName) {
      trainsScheduleModel.setSort(trainsScheduleModel.SORTBYNAME);
    } else if (ae.getSource() == sortByTime) {
      trainsScheduleModel.setSort(trainsScheduleModel.SORTBYTIME);
    } else if (ae.getSource() == noneButton) {
      enableButtons(false);
      commentTextArea.setText(""); // no text for the noneButton
      // must be one of the schedule radio buttons
    } else {
      enableButtons(true);
      // update comment field
      TrainSchedule ts = trainScheduleManager.getScheduleById(getSelectedScheduleId());
      commentTextArea.setText(ts.getComment());
    }
  }

  // add, build, print, switch lists, terminate, and save buttons
  public void buttonActionPerformed(java.awt.event.ActionEvent ae) {
    log.debug("button activated");
    if (ae.getSource() == clearButton) {
      updateCheckboxes(false);
    }
    if (ae.getSource() == selectButton) {
      updateCheckboxes(true);
    }
    if (ae.getSource() == applyButton) {
      applySchedule();
    }
    if (ae.getSource() == buildButton) {
      switchListsButton.setEnabled(false);
      // uses a thread which allows table updates during build
      trainManager.buildSelectedTrains(getSortByList());
    }
    if (ae.getSource() == printButton) {
      trainManager.printSelectedTrains(getSortByList());
    }
    if (ae.getSource() == switchListsButton) {
      trainScheduleManager.buildSwitchLists();
    }
    if (ae.getSource() == terminateButton) {
      trainManager.terminateSelectedTrains(getSortByList());
    }
    if (ae.getSource() == activateButton) {
      trainManager.setTrainSecheduleActiveId(getSelectedScheduleId());
      activateButton.setEnabled(false);
    }
    if (ae.getSource() == saveButton) {
      storeValues();
      if (Setup.isCloseWindowOnSaveEnabled()) {
        dispose();
      }
    }
  }

  /*
   * Update radio button names in the same order as the table
   */
  private void updateControlPanel() {
    schedule.removeAll();
    noneButton.setName(""); // Name holds schedule id for the selected radio button
    noneButton.setSelected(true);
    commentTextArea.setText(""); // no text for the noneButton
    enableButtons(false);
    schedule.add(noneButton);
    schGroup.add(noneButton);

    for (int i = trainsScheduleModel.getFixedColumn();
        i < trainsScheduleModel.getColumnCount();
        i++) {
      log.debug("Column name: {}", trainsScheduleTable.getColumnName(i));
      TrainSchedule ts =
          trainScheduleManager.getScheduleByName(trainsScheduleTable.getColumnName(i));
      if (ts != null) {
        JRadioButton b = new JRadioButton();
        b.setText(ts.getName());
        b.setName(ts.getId());
        schedule.add(b);
        schGroup.add(b);
        addRadioButtonAction(b);
        if (b.getName().equals(trainManager.getTrainScheduleActiveId())) {
          b.setSelected(true);
          enableButtons(true);
          // update comment field
          commentTextArea.setText(ts.getComment());
        }
      }
    }
    schedule.revalidate();
  }

  private void updateCheckboxes(boolean selected) {
    TrainSchedule ts = trainScheduleManager.getScheduleById(getSelectedScheduleId());
    if (ts != null) {
      for (Train train : trainManager.getTrainsByIdList()) {
        if (selected) {
          ts.addTrainId(train.getId());
        } else {
          ts.removeTrainId(train.getId());
        }
      }
    }
  }

  private void applySchedule() {
    TrainSchedule ts = trainScheduleManager.getScheduleById(getSelectedScheduleId());
    if (ts != null) {
      for (Train train : trainManager.getTrainsByIdList()) {
        train.setBuildEnabled(ts.containsTrainId(train.getId()));
      }
    }
  }

  private String getSelectedScheduleId() {
    AbstractButton b;
    Enumeration<AbstractButton> en = schGroup.getElements();
    while (en.hasMoreElements()) {
      b = en.nextElement();
      if (b.isSelected()) {
        log.debug("schedule radio button " + b.getText());
        return b.getName();
      }
    }
    return null;
  }

  private void enableButtons(boolean enable) {
    selectButton.setEnabled(enable);
    clearButton.setEnabled(enable);
    applyButton.setEnabled(enable);
    buildButton.setEnabled(enable);
    printButton.setEnabled(enable);
    switchListsButton.setEnabled(enable);
    terminateButton.setEnabled(enable);

    log.debug(
        "Selected id: {}, Active id: {}",
        getSelectedScheduleId(),
        trainManager.getTrainScheduleActiveId());

    activateButton.setEnabled(
        getSelectedScheduleId() != null
            && !getSelectedScheduleId().equals(trainManager.getTrainScheduleActiveId()));

    commentTextArea.setEnabled(enable);
  }

  private List<Train> getSortByList() {
    if (sortByTime.isSelected()) {
      return trainManager.getTrainsByTimeList();
    } else {
      return trainManager.getTrainsByNameList();
    }
  }

  private void setSwitchListButtonText() {
    if (!Setup.isSwitchListRealTime()) {
      switchListsButton.setText(Bundle.getMessage("Update"));
    } else if (trainManager.isPrintPreviewEnabled()) {
      switchListsButton.setText(Bundle.getMessage("PreviewSwitchLists"));
    } else {
      switchListsButton.setText(Bundle.getMessage("PrintSwitchLists"));
    }
  }

  // Modifies button text and tool tips
  private void setPrintButtonText() {
    if (trainManager.isPrintPreviewEnabled()) {
      printButton.setText(Bundle.getMessage("Preview"));
      printButton.setToolTipText(Bundle.getMessage("PreviewSelectedTip"));
    } else {
      printButton.setText(Bundle.getMessage("Print"));
      printButton.setToolTipText(Bundle.getMessage("PrintSelectedTip"));
    }
  }

  //    private void buildSwitchList() {
  //        TrainSwitchLists trainSwitchLists = new TrainSwitchLists();
  //        for (Location location : locationManager.getLocationsByNameList()) {
  //            if (location.isSwitchListEnabled()) {
  //                trainSwitchLists.buildSwitchList(location);
  //                // // print or print changes
  //                if (Setup.isSwitchListRealTime() &&
  // !location.getStatus().equals(Location.PRINTED)) {
  //                    trainSwitchLists.printSwitchList(location,
  // trainManager.isPrintPreviewEnabled());
  //                }
  //            }
  //        }
  //        // set trains switch lists printed
  //        trainManager.setTrainsSwitchListStatus(Train.PRINTED);
  //    }

  private void updateSwitchListButton() {
    log.debug("update switch list button");
    List<Location> locations = locationManager.getList();
    for (Location location : locations) {
      if (location != null
          && location.isSwitchListEnabled()
          && location.getStatus().equals(Location.MODIFIED)) {
        switchListsButton.setBackground(Color.RED);
        return;
      }
    }
    switchListsButton.setBackground(Color.GREEN);
  }

  protected void storeValues() {
    // Save comment
    TrainSchedule ts = trainScheduleManager.getScheduleById(getSelectedScheduleId());
    if (ts != null) {
      ts.setComment(commentTextArea.getText());
    }
    //        updateControlPanel();
    saveTableDetails(trainsScheduleTable);
    OperationsXml.save();
  }

  public void dispose() {
    Setup.removePropertyChangeListener(this);
    trainManager.removePropertyChangeListener(this);
    trainScheduleManager.removePropertyChangeListener(this);
    removePropertyChangeTrainSchedules();
    removePropertyChangeLocations();
    trainsScheduleModel.dispose();
    super.dispose();
  }

  private void addPropertyChangeLocations() {
    for (Location location : locationManager.getList()) {
      location.addPropertyChangeListener(this);
    }
  }

  private void removePropertyChangeLocations() {
    for (Location location : locationManager.getList()) {
      location.removePropertyChangeListener(this);
    }
  }

  private void addPropertyChangeTrainSchedules() {
    List<TrainSchedule> trainSchedules = trainScheduleManager.getSchedulesByIdList();
    for (TrainSchedule ts : trainSchedules) {
      ts.addPropertyChangeListener(this);
    }
  }

  private void removePropertyChangeTrainSchedules() {
    List<TrainSchedule> trainSchedules = trainScheduleManager.getSchedulesByIdList();
    for (TrainSchedule ts : trainSchedules) {
      ts.removePropertyChangeListener(this);
    }
  }

  public void propertyChange(PropertyChangeEvent e) {
    if (Control.showProperty)
      log.debug(
          "Property change {} old: {} new: {}",
          e.getPropertyName(),
          e.getOldValue(),
          e.getNewValue());
    if (e.getPropertyName().equals(TrainScheduleManager.LISTLENGTH_CHANGED_PROPERTY)
        || e.getPropertyName().equals(TrainSchedule.NAME_CHANGED_PROPERTY)) {
      updateControlPanel();
    }
    if (e.getPropertyName().equals(TrainManager.PRINTPREVIEW_CHANGED_PROPERTY)) {
      setPrintButtonText();
      setSwitchListButtonText();
    }
    if (e.getPropertyName().equals(TrainManager.TRAINS_BUILT_CHANGED_PROPERTY)) {
      switchListsButton.setEnabled(true);
    }
    if (e.getPropertyName().equals(Setup.REAL_TIME_PROPERTY_CHANGE)) {
      setSwitchListButtonText();
    }
    if (e.getPropertyName().equals(Location.STATUS_CHANGED_PROPERTY)
        || e.getPropertyName().equals(Location.SWITCHLIST_CHANGED_PROPERTY)) {
      updateSwitchListButton();
    }
  }

  private static final Logger log =
      LoggerFactory.getLogger(TrainsScheduleTableFrame.class.getName());
}
예제 #7
0
/**
 * Frame for adding and editing the train roster for operations.
 *
 * @author Bob Jacobsen Copyright (C) 2001
 * @author Daniel Boudreau Copyright (C) 2008, 2009, 2010, 2011, 2012, 2013, 2014
 * @version $Revision$
 */
public class TrainsTableFrame extends OperationsFrame implements java.beans.PropertyChangeListener {

  /** */
  private static final long serialVersionUID = 4237149773850338265L;

  public static final String MOVE = Bundle.getMessage("Move");
  public static final String TERMINATE = Bundle.getMessage("Terminate");
  public static final String RESET = Bundle.getMessage("Reset");
  public static final String CONDUCTOR = Bundle.getMessage("Conductor");

  CarManagerXml carManagerXml = CarManagerXml.instance(); // load cars
  EngineManagerXml engineManagerXml = EngineManagerXml.instance(); // load engines
  TrainManager trainManager = TrainManager.instance();
  TrainManagerXml trainManagerXml = TrainManagerXml.instance();
  LocationManager locationManager = LocationManager.instance();

  TrainsTableModel trainsModel;
  TableSorter sorter;
  JTable trainsTable;
  JScrollPane trainsPane;

  // labels
  JLabel numTrains = new JLabel();
  JLabel textTrains = new JLabel(Bundle.getMessage("Trains").toLowerCase());
  JLabel textSep1 = new JLabel("      ");

  // radio buttons
  JRadioButton showTime = new JRadioButton(Bundle.getMessage("Time"));
  JRadioButton showId = new JRadioButton(Bundle.getMessage("Id"));

  JRadioButton moveRB = new JRadioButton(MOVE);
  JRadioButton terminateRB = new JRadioButton(TERMINATE);
  JRadioButton resetRB = new JRadioButton(RESET);
  JRadioButton conductorRB = new JRadioButton(CONDUCTOR);

  // major buttons
  JButton addButton = new JButton(Bundle.getMessage("Add"));
  JButton buildButton = new JButton(Bundle.getMessage("Build"));
  JButton printButton = new JButton(Bundle.getMessage("Print"));
  JButton openFileButton = new JButton(Bundle.getMessage("OpenFile"));
  JButton runFileButton = new JButton(Bundle.getMessage("RunFile"));
  JButton switchListsButton = new JButton(Bundle.getMessage("SwitchLists"));
  JButton terminateButton = new JButton(Bundle.getMessage("Terminate"));
  JButton saveButton = new JButton(Bundle.getMessage("SaveBuilds"));

  // check boxes
  JCheckBox buildMsgBox = new JCheckBox(Bundle.getMessage("BuildMessages"));
  JCheckBox buildReportBox = new JCheckBox(Bundle.getMessage("BuildReport"));
  JCheckBox printPreviewBox = new JCheckBox(Bundle.getMessage("Preview"));
  JCheckBox openFileBox = new JCheckBox(Bundle.getMessage("OpenFile"));
  JCheckBox runFileBox = new JCheckBox(Bundle.getMessage("RunFile"));
  JCheckBox showAllBox = new JCheckBox(Bundle.getMessage("ShowAllTrains"));

  public TrainsTableFrame() {
    super();

    updateTitle();

    // create ShutDownTasks
    createShutDownTask();
    // always check for dirty operations files
    setModifiedFlag(true);

    // general GUI configuration
    getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

    // Set up the jtable in a Scroll Pane..
    trainsModel = new TrainsTableModel();
    sorter = new TableSorter(trainsModel);
    trainsTable = new JTable(sorter);
    sorter.setTableHeader(trainsTable.getTableHeader());
    trainsPane = new JScrollPane(trainsTable);
    trainsModel.initTable(trainsTable, this);

    // Set up the control panel
    // row 1
    JPanel cp1 = new JPanel();
    cp1.setLayout(new BoxLayout(cp1, BoxLayout.X_AXIS));

    JPanel show = new JPanel();
    show.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("ShowClickToSort")));
    show.add(showTime);
    show.add(showId);

    JPanel options = new JPanel();
    options.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Options")));
    options.add(showAllBox);
    options.add(buildMsgBox);
    options.add(buildReportBox);
    options.add(printPreviewBox);
    options.add(openFileBox);
    options.add(runFileBox);

    JPanel action = new JPanel();
    action.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Action")));
    action.add(moveRB);
    action.add(conductorRB);
    action.add(terminateRB);
    action.add(resetRB);

    cp1.add(show);
    cp1.add(options);
    cp1.add(action);

    // tool tips, see setPrintButtonText() for more tool tips
    addButton.setToolTipText(Bundle.getMessage("AddTrain"));
    buildButton.setToolTipText(Bundle.getMessage("BuildSelectedTip"));
    switchListsButton.setToolTipText(Bundle.getMessage("PreviewPrintSwitchLists"));

    terminateButton.setToolTipText(Bundle.getMessage("TerminateSelectedTip"));
    saveButton.setToolTipText(Bundle.getMessage("SaveBuildsTip"));
    openFileButton.setToolTipText(Bundle.getMessage("OpenFileButtonTip"));
    runFileButton.setToolTipText(Bundle.getMessage("RunFileButtonTip"));
    buildMsgBox.setToolTipText(Bundle.getMessage("BuildMessagesTip"));
    printPreviewBox.setToolTipText(Bundle.getMessage("PreviewTip"));
    openFileBox.setToolTipText(Bundle.getMessage("OpenFileTip"));
    runFileBox.setToolTipText(Bundle.getMessage("RunFileTip"));
    showAllBox.setToolTipText(Bundle.getMessage("ShowAllTrainsTip"));

    moveRB.setToolTipText(Bundle.getMessage("MoveTip"));
    terminateRB.setToolTipText(Bundle.getMessage("TerminateTip"));
    resetRB.setToolTipText(Bundle.getMessage("ResetTip"));

    // row 2
    JPanel addTrain = new JPanel();
    addTrain.setBorder(BorderFactory.createTitledBorder(""));
    addTrain.add(numTrains);
    addTrain.add(textTrains);
    addTrain.add(textSep1);
    addTrain.add(addButton);

    numTrains.setText(Integer.toString(trainManager.getNumEntries()));

    JPanel select = new JPanel();
    select.setBorder(BorderFactory.createTitledBorder(""));
    select.add(buildButton);
    select.add(printButton);
    select.add(openFileButton);
    select.add(runFileButton);
    select.add(switchListsButton);
    select.add(terminateButton);

    JPanel save = new JPanel();
    save.setBorder(BorderFactory.createTitledBorder(""));
    save.add(saveButton);

    JPanel cp2 = new JPanel();
    cp2.setLayout(new BoxLayout(cp2, BoxLayout.X_AXIS));
    cp2.add(addTrain);
    cp2.add(select);
    cp2.add(save);

    // place controls in scroll pane
    JPanel controlPanel = new JPanel();
    controlPanel.setLayout(new BoxLayout(controlPanel, BoxLayout.Y_AXIS));
    controlPanel.add(cp1);
    controlPanel.add(cp2);

    JScrollPane controlPane = new JScrollPane(controlPanel);

    getContentPane().add(trainsPane);
    getContentPane().add(controlPane);

    // setup buttons
    addButtonAction(addButton);
    addButtonAction(buildButton);
    addButtonAction(printButton);
    addButtonAction(openFileButton);
    addButtonAction(runFileButton);
    addButtonAction(switchListsButton);
    addButtonAction(terminateButton);
    addButtonAction(saveButton);

    ButtonGroup showGroup = new ButtonGroup();
    showGroup.add(showTime);
    showGroup.add(showId);
    showTime.setSelected(true);

    ButtonGroup actionGroup = new ButtonGroup();
    actionGroup.add(moveRB);
    actionGroup.add(conductorRB);
    actionGroup.add(terminateRB);
    actionGroup.add(resetRB);

    addRadioButtonAction(showTime);
    addRadioButtonAction(showId);

    addRadioButtonAction(moveRB);
    addRadioButtonAction(terminateRB);
    addRadioButtonAction(resetRB);
    addRadioButtonAction(conductorRB);

    buildMsgBox.setSelected(trainManager.isBuildMessagesEnabled());
    buildReportBox.setSelected(trainManager.isBuildReportEnabled());
    printPreviewBox.setSelected(trainManager.isPrintPreviewEnabled());
    openFileBox.setSelected(trainManager.isOpenFileEnabled());
    runFileBox.setSelected(trainManager.isRunFileEnabled());
    showAllBox.setSelected(trainsModel.isShowAll());

    // show open files only if create csv is enabled
    updateRunAndOpenButtons();

    addCheckBoxAction(buildMsgBox);
    addCheckBoxAction(buildReportBox);
    addCheckBoxAction(printPreviewBox);
    addCheckBoxAction(showAllBox);
    addCheckBoxAction(openFileBox);
    addCheckBoxAction(runFileBox);

    // Set the button text to Print or Preview
    setPrintButtonText();
    // Set the train action button text to Move or Terminate
    setTrainActionButton();

    // build menu
    JMenuBar menuBar = new JMenuBar();
    JMenu toolMenu = new JMenu(Bundle.getMessage("Tools"));
    toolMenu.add(new OptionAction(Bundle.getMessage("TitleOptions")));
    toolMenu.add(new PrintOptionAction());
    toolMenu.add(new BuildReportOptionAction());
    toolMenu.add(new TrainsByCarTypeAction(Bundle.getMessage("TitleModifyTrains")));
    toolMenu.add(new TrainByCarTypeAction(Bundle.getMessage("MenuItemShowCarTypes"), null));
    toolMenu.add(new ChangeDepartureTimesAction(Bundle.getMessage("TitleChangeDepartureTime")));
    toolMenu.add(new TrainsTableSetColorAction());
    toolMenu.add(new TrainsScheduleAction(Bundle.getMessage("TitleTimeTableTrains")));
    toolMenu.add(new TrainCopyAction(Bundle.getMessage("TitleTrainCopy")));
    toolMenu.add(new TrainsScriptAction(Bundle.getMessage("MenuItemScripts"), this));
    toolMenu.add(
        new PrintSavedTrainManifestAction(Bundle.getMessage("MenuItemPrintSavedManifest"), false));
    toolMenu.add(
        new PrintSavedTrainManifestAction(Bundle.getMessage("MenuItemPreviewSavedManifest"), true));
    toolMenu.add(new SetupExcelProgramFrameAction(Bundle.getMessage("MenuItemSetupExcelProgram")));
    toolMenu.add(new ExportTrainRosterAction());
    toolMenu.add(
        new PrintTrainsAction(Bundle.getMessage("MenuItemPrint"), new Frame(), false, this));
    toolMenu.add(
        new PrintTrainsAction(Bundle.getMessage("MenuItemPreview"), new Frame(), true, this));

    menuBar.add(toolMenu);
    menuBar.add(new jmri.jmrit.operations.OperationsMenu());
    setJMenuBar(menuBar);

    // add help menu to window
    addHelpMenu("package.jmri.jmrit.operations.Operations_Trains", true); // NOI18N

    initMinimumSize();

    addHorizontalScrollBarKludgeFix(controlPane, controlPanel);

    // listen for timetable changes
    trainManager.addPropertyChangeListener(this);
    Setup.addPropertyChangeListener(this);
    // listen for location switch list changes
    addPropertyChangeLocations();

    // auto save
    new AutoSave();
  }

  public void radioButtonActionPerformed(java.awt.event.ActionEvent ae) {
    log.debug("radio button activated");
    if (ae.getSource() == showId) {
      trainsModel.setSort(trainsModel.SORTBYID);
    }
    if (ae.getSource() == showTime) {
      trainsModel.setSort(trainsModel.SORTBYTIME);
    }
    if (ae.getSource() == moveRB) {
      trainManager.setTrainsFrameTrainAction(MOVE);
    }
    if (ae.getSource() == terminateRB) {
      trainManager.setTrainsFrameTrainAction(TERMINATE);
    }
    if (ae.getSource() == resetRB) {
      trainManager.setTrainsFrameTrainAction(RESET);
    }
    if (ae.getSource() == conductorRB) {
      trainManager.setTrainsFrameTrainAction(CONDUCTOR);
    }
  }

  TrainSwitchListEditFrame tslef;

  // add, build, print, switch lists, terminate, and save buttons
  public void buttonActionPerformed(java.awt.event.ActionEvent ae) {
    // log.debug("train button activated");
    if (ae.getSource() == addButton) {
      new TrainEditFrame(null);
    }
    if (ae.getSource() == buildButton) {
      // uses a thread which allows table updates during build
      trainManager.buildSelectedTrains(getSortByList());
    }
    if (ae.getSource() == printButton) {
      trainManager.printSelectedTrains(getSortByList());
    }
    if (ae.getSource() == openFileButton) {
      // open the csv files
      List<Train> trains = getSortByList();
      for (Train train : trains) {
        if (train.isBuildEnabled()) {
          if (!train.isBuilt() && trainManager.isBuildMessagesEnabled()) {
            JOptionPane.showMessageDialog(
                this,
                MessageFormat.format(
                    Bundle.getMessage("NeedToBuildBeforeOpenFile"),
                    new Object[] {
                      train.getName(),
                      (trainManager.isPrintPreviewEnabled()
                          ? Bundle.getMessage("preview")
                          : Bundle.getMessage("print"))
                    }),
                MessageFormat.format(
                    Bundle.getMessage("CanNotPrintManifest"),
                    new Object[] {
                      trainManager.isPrintPreviewEnabled()
                          ? Bundle.getMessage("preview")
                          : Bundle.getMessage("print")
                    }),
                JOptionPane.ERROR_MESSAGE);
          } else if (train.isBuilt()) {
            train.openFile();
          }
        }
      }
    }
    if (ae.getSource() == runFileButton) {
      // Processes the CSV Manifest files using an external custom program.
      if (!TrainCustomManifest.manifestCreatorFileExists()) {
        log.warn(
            "Manifest creator file not found!, directory name: "
                + TrainCustomManifest.getDirectoryName()
                + ", file name: "
                + TrainCustomManifest.getFileName()); // NOI18N
        JOptionPane.showMessageDialog(
            this,
            MessageFormat.format(
                Bundle.getMessage("LoadDirectoryNameFileName"),
                new Object[] {
                  TrainCustomManifest.getDirectoryName(), TrainCustomManifest.getFileName()
                }),
            Bundle.getMessage("ManifestCreatorNotFound"),
            JOptionPane.ERROR_MESSAGE);
        return;
      }
      List<Train> trains = getSortByList();
      for (Train train : trains) {
        if (train.isBuildEnabled()) {
          if (!train.isBuilt() && trainManager.isBuildMessagesEnabled()) {
            JOptionPane.showMessageDialog(
                this,
                MessageFormat.format(
                    Bundle.getMessage("NeedToBuildBeforeRunFile"),
                    new Object[] {
                      train.getName(),
                      (trainManager.isPrintPreviewEnabled()
                          ? Bundle.getMessage("preview")
                          : Bundle.getMessage("print"))
                    }),
                MessageFormat.format(
                    Bundle.getMessage("CanNotPrintManifest"),
                    new Object[] {
                      trainManager.isPrintPreviewEnabled()
                          ? Bundle.getMessage("preview")
                          : Bundle.getMessage("print")
                    }),
                JOptionPane.ERROR_MESSAGE);
          } else if (train.isBuilt()) {
            // Make sure our csv manifest file exists for this Train.
            File csvFile = train.createCSVManifestFile();
            // Add it to our collection to be processed.
            TrainCustomManifest.addCVSFile(csvFile);
          }
        }
      }

      // Now run the user specified custom Manifest processor program
      TrainCustomManifest.process();
    }
    if (ae.getSource() == switchListsButton) {
      if (tslef != null) {
        tslef.dispose();
      }
      tslef = new TrainSwitchListEditFrame();
      tslef.initComponents();
    }
    if (ae.getSource() == terminateButton) {
      trainManager.terminateSelectedTrains(getSortByList());
    }
    if (ae.getSource() == saveButton) {
      storeValues();
    }
  }

  int _status = TableSorter.ASCENDING;

  protected String getSortBy() {
    // set the defaults
    String sortBy = TrainsTableModel.TIMECOLUMNNAME;
    _status = TableSorter.ASCENDING;
    // now look to see if a sort is active
    for (int i = 0; i < sorter.getColumnCount(); i++) {
      String name = sorter.getColumnName(i);
      int status = sorter.getSortingStatus(i);
      // log.debug("Column " + name + " status " + status);
      if (status != TableSorter.NOT_SORTED && !name.equals("")) {
        sortBy = name;
        _status = status;
        break;
      }
    }
    return sortBy;
  }

  public List<Train> getSortByList() {
    List<Train> sysList;
    String sortBy = getSortBy();
    if (sortBy.equals(TrainsTableModel.IDCOLUMNNAME)) {
      sysList = trainManager.getTrainsByIdList();
    } else if (sortBy.equals(TrainsTableModel.TIMECOLUMNNAME)) {
      sysList = trainManager.getTrainsByTimeList();
    } else if (sortBy.equals(TrainsTableModel.DEPARTSCOLUMNNAME)) {
      sysList = trainManager.getTrainsByDepartureList();
    } else if (sortBy.equals(TrainsTableModel.TERMINATESCOLUMNNAME)) {
      sysList = trainManager.getTrainsByTerminatesList();
    } else if (sortBy.equals(TrainsTableModel.ROUTECOLUMNNAME)) {
      sysList = trainManager.getTrainsByRouteList();
    } else if (sortBy.equals(TrainsTableModel.STATUSCOLUMNNAME)) {
      sysList = trainManager.getTrainsByStatusList();
    } else if (sortBy.equals(TrainsTableModel.DESCRIPTIONCOLUMNNAME)) {
      sysList = trainManager.getTrainsByDescriptionList();
    } else {
      sysList = trainManager.getTrainsByNameList();
    }
    return sysList;
  }

  // Modifies button text and tool tips
  private void setPrintButtonText() {
    if (printPreviewBox.isSelected()) {
      printButton.setText(Bundle.getMessage("Preview"));
      printButton.setToolTipText(Bundle.getMessage("PreviewSelectedTip"));
      buildReportBox.setToolTipText(Bundle.getMessage("BuildReportPreviewTip"));
    } else {
      printButton.setText(Bundle.getMessage("Print"));
      printButton.setToolTipText(Bundle.getMessage("PrintSelectedTip"));
      buildReportBox.setToolTipText(Bundle.getMessage("BuildReportPrintTip"));
    }
  }

  private void setTrainActionButton() {
    moveRB.setSelected(trainManager.getTrainsFrameTrainAction().equals(TrainsTableFrame.MOVE));
    terminateRB.setSelected(
        trainManager.getTrainsFrameTrainAction().equals(TrainsTableFrame.TERMINATE));
    resetRB.setSelected(trainManager.getTrainsFrameTrainAction().equals(TrainsTableFrame.RESET));
    conductorRB.setSelected(
        trainManager.getTrainsFrameTrainAction().equals(TrainsTableFrame.CONDUCTOR));
  }

  public void checkBoxActionPerformed(java.awt.event.ActionEvent ae) {
    if (ae.getSource() == buildMsgBox) {
      trainManager.setBuildMessagesEnabled(buildMsgBox.isSelected());
    }
    if (ae.getSource() == buildReportBox) {
      trainManager.setBuildReportEnabled(buildReportBox.isSelected());
    }
    if (ae.getSource() == printPreviewBox) {
      trainManager.setPrintPreviewEnabled(printPreviewBox.isSelected());
      setPrintButtonText(); // set the button text for Print or Preview
    }
    if (ae.getSource() == openFileBox) {
      trainManager.setOpenFileEnabled(openFileBox.isSelected());
      runFileBox.setSelected(false);
      trainManager.setRunFileEnabled(false);
    }
    if (ae.getSource() == runFileBox) {
      trainManager.setRunFileEnabled(runFileBox.isSelected());
      openFileBox.setSelected(false);
      trainManager.setOpenFileEnabled(false);
    }
    if (ae.getSource() == showAllBox) {
      trainsModel.setShowAll(showAllBox.isSelected());
    }
  }

  private void updateTitle() {
    String title = Bundle.getMessage("TitleTrainsTable");
    TrainSchedule sch =
        TrainScheduleManager.instance().getScheduleById(trainManager.getTrainScheduleActiveId());
    if (sch != null) {
      title = title + " (" + sch.getName() + ")";
    }
    setTitle(title);
  }

  private void updateSwitchListButton() {
    log.debug("update switch list button");
    List<Location> locations = locationManager.getList();
    for (Location location : locations) {
      if (location != null
          && location.isSwitchListEnabled()
          && location.getStatus().equals(Location.MODIFIED)) {
        switchListsButton.setBackground(Color.RED);
        return;
      }
    }
    switchListsButton.setBackground(Color.GREEN);
  }

  // show open files only if create csv is enabled
  private void updateRunAndOpenButtons() {
    openFileBox.setVisible(Setup.isGenerateCsvManifestEnabled());
    openFileButton.setVisible(Setup.isGenerateCsvManifestEnabled());
    runFileBox.setVisible(Setup.isGenerateCsvManifestEnabled());
    runFileButton.setVisible(Setup.isGenerateCsvManifestEnabled());
  }

  private synchronized void addPropertyChangeLocations() {
    List<Location> locations = locationManager.getList();
    for (Location location : locations) {
      location.addPropertyChangeListener(this);
    }
  }

  private synchronized void removePropertyChangeLocations() {
    List<Location> locations = locationManager.getList();
    for (Location location : locations) {
      location.removePropertyChangeListener(this);
    }
  }

  public void dispose() {
    /*
     * all JMRI window position and size are now saved in user preference file
     * trainManager.setTrainsFrameTableColumnWidths(getCurrentTableColumnWidths()); // save column widths
     * trainManager.setTrainsFrame(null);
     */
    trainsModel.dispose();
    trainManager.runShutDownScripts();
    trainManager.removePropertyChangeListener(this);
    Setup.removePropertyChangeListener(this);
    removePropertyChangeLocations();
    super.dispose();
  }

  protected void handleModified() {
    if (Setup.isAutoSaveEnabled()) {
      storeValues();
      return;
    }
    if (OperationsXml.areFilesDirty()) {
      int result =
          javax.swing.JOptionPane.showOptionDialog(
              this,
              Bundle.getMessage("PromptQuitWindowNotWritten"),
              Bundle.getMessage("PromptSaveQuit"),
              javax.swing.JOptionPane.YES_NO_OPTION,
              javax.swing.JOptionPane.WARNING_MESSAGE,
              null, // icon
              new String[] {
                ResourceBundle.getBundle("jmri.util.UtilBundle").getString("WarnYesSave"), // NOI18N
                ResourceBundle.getBundle("jmri.util.UtilBundle").getString("WarnNoClose")
              }, // NOI18N
              ResourceBundle.getBundle("jmri.util.UtilBundle").getString("WarnYesSave"));
      if (result == javax.swing.JOptionPane.NO_OPTION) {
        return;
      }
      // user wants to save
      storeValues();
    }
  }

  protected void storeValues() {
    super.storeValues();
    saveTableDetails(trainsTable);
  }

  public void propertyChange(java.beans.PropertyChangeEvent e) {
    if (Control.showProperty) {
      log.debug(
          "Property change: ({}) old: ({}) new: ({})",
          e.getPropertyName(),
          e.getOldValue(),
          e.getNewValue());
    }
    if (e.getPropertyName().equals(TrainManager.ACTIVE_TRAIN_SCHEDULE_ID)) {
      updateTitle();
    }
    if (e.getPropertyName().equals(Location.STATUS_CHANGED_PROPERTY)
        || e.getPropertyName().equals(Location.SWITCHLIST_CHANGED_PROPERTY)) {
      updateSwitchListButton();
    }
    if (e.getPropertyName().equals(Setup.MANIFEST_CSV_PROPERTY_CHANGE)) {
      updateRunAndOpenButtons();
    }
    if (e.getPropertyName().equals(TrainManager.LISTLENGTH_CHANGED_PROPERTY)) {
      numTrains.setText(Integer.toString(trainManager.getNumEntries()));
    }
  }

  static Logger log = LoggerFactory.getLogger(TrainsTableFrame.class.getName());
}
예제 #8
0
 private void removePropertyChangeTracks() {
   for (Track track : LocationManager.instance().getTracks(Track.SPUR)) {
     track.removePropertyChangeListener(this);
   }
 }
예제 #9
0
 private void addPropertyChangeTracks() {
   // only spurs have schedules
   for (Track track : LocationManager.instance().getTracks(Track.SPUR)) {
     track.addPropertyChangeListener(this);
   }
 }
예제 #10
0
/**
 * Frame for user edit of engine
 *
 * @author Dan Boudreau Copyright (C) 2008, 2011
 * @version $Revision$
 */
public class EngineEditFrame extends OperationsFrame implements java.beans.PropertyChangeListener {

  EngineManager manager = EngineManager.instance();
  EngineManagerXml managerXml = EngineManagerXml.instance();
  EngineModels engineModels = EngineModels.instance();
  EngineTypes engineTypes = EngineTypes.instance();
  EngineLengths engineLengths = EngineLengths.instance();
  CarManagerXml carManagerXml = CarManagerXml.instance();
  LocationManager locationManager = LocationManager.instance();

  Engine _engine;

  // major buttons
  JButton editRoadButton = new JButton(Bundle.getMessage("Edit"));
  JButton clearRoadNumberButton = new JButton(Bundle.getMessage("Clear"));
  JButton editModelButton = new JButton(Bundle.getMessage("Edit"));
  JButton editTypeButton = new JButton(Bundle.getMessage("Edit"));
  JButton editLengthButton = new JButton(Bundle.getMessage("Edit"));
  JButton fillWeightButton = new JButton();
  JButton editConsistButton = new JButton(Bundle.getMessage("Edit"));
  JButton editOwnerButton = new JButton(Bundle.getMessage("Edit"));

  JButton saveButton = new JButton(Bundle.getMessage("Save"));
  JButton deleteButton = new JButton(Bundle.getMessage("Delete"));
  JButton addButton = new JButton(Bundle.getMessage("Add"));

  // check boxes
  JCheckBox bUnitCheckBox = new JCheckBox(Bundle.getMessage("BUnit"));

  // text field
  JTextField roadNumberTextField = new JTextField(Control.max_len_string_road_number);
  JTextField builtTextField = new JTextField(Control.max_len_string_built_name + 3);
  JTextField hpTextField = new JTextField(8);
  JTextField weightTextField = new JTextField(Control.max_len_string_weight_name);
  JTextField commentTextField = new JTextField(35);
  JTextField valueTextField = new JTextField(8);

  // combo boxes
  JComboBox<String> roadComboBox = CarRoads.instance().getComboBox();
  JComboBox<String> modelComboBox = engineModels.getComboBox();
  JComboBox<String> typeComboBox = engineTypes.getComboBox();
  JComboBox<String> lengthComboBox = engineLengths.getComboBox();
  JComboBox<String> ownerComboBox = CarOwners.instance().getComboBox();
  JComboBox<Location> locationBox = locationManager.getComboBox();
  JComboBox<Track> trackLocationBox = new JComboBox<>();
  JComboBox<String> consistComboBox = manager.getConsistComboBox();
  JComboBox<IdTag> rfidComboBox = new JComboBox<IdTag>();

  public static final String ROAD = Bundle.getMessage("Road");
  public static final String MODEL = Bundle.getMessage("Model");
  public static final String TYPE = Bundle.getMessage("Type");
  public static final String COLOR = Bundle.getMessage("Color");
  public static final String LENGTH = Bundle.getMessage("Length");
  public static final String OWNER = Bundle.getMessage("Owner");
  public static final String CONSIST = Bundle.getMessage("Consist");

  public EngineEditFrame() {
    super();
  }

  public void initComponents() {
    // set tips
    builtTextField.setToolTipText(Bundle.getMessage("buildDateTip"));
    rfidComboBox.setToolTipText(Bundle.getMessage("TipRfid"));
    editRoadButton.setToolTipText(
        MessageFormat.format(
            Bundle.getMessage("TipAddDeleteReplace"),
            new Object[] {Bundle.getMessage("Road").toLowerCase()}));
    editTypeButton.setToolTipText(
        MessageFormat.format(
            Bundle.getMessage("TipAddDeleteReplace"),
            new Object[] {Bundle.getMessage("Type").toLowerCase()}));
    editModelButton.setToolTipText(
        MessageFormat.format(
            Bundle.getMessage("TipAddDeleteReplace"),
            new Object[] {Bundle.getMessage("Model").toLowerCase()}));
    editLengthButton.setToolTipText(
        MessageFormat.format(
            Bundle.getMessage("TipAddDeleteReplace"),
            new Object[] {Bundle.getMessage("Length").toLowerCase()}));
    editOwnerButton.setToolTipText(
        MessageFormat.format(
            Bundle.getMessage("TipAddDeleteReplace"),
            new Object[] {Bundle.getMessage("Owner").toLowerCase()}));
    editConsistButton.setToolTipText(
        MessageFormat.format(
            Bundle.getMessage("TipAddDeleteReplace"),
            new Object[] {Bundle.getMessage("Consist").toLowerCase()}));
    bUnitCheckBox.setToolTipText(Bundle.getMessage("TipBoosterUnit"));

    // create panel
    JPanel pPanel = new JPanel();
    pPanel.setLayout(new BoxLayout(pPanel, BoxLayout.Y_AXIS));

    // Layout the panel by rows
    // row 1
    JPanel pRoad = new JPanel();
    pRoad.setLayout(new GridBagLayout());
    pRoad.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Road")));
    addItem(pRoad, roadComboBox, 1, 0);
    addItem(pRoad, editRoadButton, 2, 0);
    pPanel.add(pRoad);

    // row 2
    JPanel pRoadNumber = new JPanel();
    pRoadNumber.setLayout(new GridBagLayout());
    pRoadNumber.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("RoadNumber")));
    addItem(pRoadNumber, roadNumberTextField, 1, 0);
    addItem(pRoadNumber, clearRoadNumberButton, 2, 0);
    pPanel.add(pRoadNumber);

    // row 3
    JPanel pModel = new JPanel();
    pModel.setLayout(new GridBagLayout());
    pModel.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Model")));
    addItem(pModel, modelComboBox, 1, 0);
    addItem(pModel, editModelButton, 2, 0);
    pPanel.add(pModel);

    // row 4
    JPanel pType = new JPanel();
    pType.setLayout(new GridBagLayout());
    pType.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Type")));
    addItem(pType, typeComboBox, 1, 0);
    addItem(pType, editTypeButton, 2, 0);
    addItem(pType, bUnitCheckBox, 1, 1);
    pPanel.add(pType);

    // row 5
    JPanel pLength = new JPanel();
    pLength.setLayout(new GridBagLayout());
    pLength.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Length")));
    addItem(pLength, lengthComboBox, 1, 0);
    addItem(pLength, editLengthButton, 2, 0);
    pPanel.add(pLength);

    // row 6
    JPanel pLocation = new JPanel();
    pLocation.setLayout(new GridBagLayout());
    pLocation.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("LocationAndTrack")));
    addItem(pLocation, locationBox, 1, 0);
    addItem(pLocation, trackLocationBox, 2, 0);
    pPanel.add(pLocation);

    // optional panel
    JPanel pOptional = new JPanel();
    pOptional.setLayout(new BoxLayout(pOptional, BoxLayout.Y_AXIS));
    JScrollPane optionPane = new JScrollPane(pOptional);
    optionPane.setBorder(
        BorderFactory.createTitledBorder(Bundle.getMessage("BorderLayoutOptional")));

    // row 11
    JPanel pWeightTons = new JPanel();
    pWeightTons.setLayout(new GridBagLayout());
    pWeightTons.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("WeightTons")));
    addItem(pWeightTons, weightTextField, 0, 0);
    pOptional.add(pWeightTons);

    // row 12
    JPanel pHp = new JPanel();
    pHp.setLayout(new GridBagLayout());
    pHp.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Hp")));
    addItem(pHp, hpTextField, 0, 0);
    pOptional.add(pHp);

    // row 13
    JPanel pConsist = new JPanel();
    pConsist.setLayout(new GridBagLayout());
    pConsist.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Consist")));
    addItem(pConsist, consistComboBox, 1, 0);
    addItem(pConsist, editConsistButton, 2, 0);
    pOptional.add(pConsist);

    // row 14
    JPanel pBuilt = new JPanel();
    pBuilt.setLayout(new GridBagLayout());
    pBuilt.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Built")));
    addItem(pBuilt, builtTextField, 1, 0);
    pOptional.add(pBuilt);

    // row 15
    JPanel pOwner = new JPanel();
    pOwner.setLayout(new GridBagLayout());
    pOwner.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Owner")));
    addItem(pOwner, ownerComboBox, 1, 0);
    addItem(pOwner, editOwnerButton, 2, 0);
    pOptional.add(pOwner);

    // row 18
    if (Setup.isValueEnabled()) {
      JPanel pValue = new JPanel();
      pValue.setLayout(new GridBagLayout());
      pValue.setBorder(BorderFactory.createTitledBorder(Setup.getValueLabel()));
      addItem(pValue, valueTextField, 1, 0);
      pOptional.add(pValue);
    }

    // row 20
    if (Setup.isRfidEnabled()) {
      JPanel pRfid = new JPanel();
      pRfid.setLayout(new GridBagLayout());
      pRfid.setBorder(BorderFactory.createTitledBorder(Setup.getRfidLabel()));
      addItem(pRfid, rfidComboBox, 1, 0);
      jmri.InstanceManager.getDefault(jmri.IdTagManager.class)
          .getNamedBeanList()
          .forEach((tag) -> rfidComboBox.addItem((jmri.IdTag) tag));
      pOptional.add(pRfid);
    }

    // row 22
    JPanel pComment = new JPanel();
    pComment.setLayout(new GridBagLayout());
    pComment.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Comment")));
    addItem(pComment, commentTextField, 1, 0);
    pOptional.add(pComment);

    // button panel
    JPanel pButtons = new JPanel();
    pButtons.setLayout(new GridBagLayout());
    addItem(pButtons, deleteButton, 0, 25);
    addItem(pButtons, addButton, 1, 25);
    addItem(pButtons, saveButton, 3, 25);

    // add panels
    getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
    getContentPane().add(pPanel);
    getContentPane().add(optionPane);
    getContentPane().add(pButtons);

    // setup buttons
    addEditButtonAction(editRoadButton);
    addButtonAction(clearRoadNumberButton);
    addEditButtonAction(editModelButton);
    addEditButtonAction(editTypeButton);
    addEditButtonAction(editLengthButton);
    addEditButtonAction(editConsistButton);
    addEditButtonAction(editOwnerButton);

    addButtonAction(deleteButton);
    addButtonAction(addButton);
    addButtonAction(saveButton);
    addButtonAction(fillWeightButton);

    // setup combobox
    addComboBoxAction(modelComboBox);
    addComboBoxAction(locationBox);

    // setup checkbox
    // build menu
    // JMenuBar menuBar = new JMenuBar();
    // JMenu toolMenu = new JMenu(Bundle.getMessage("Tools"));
    // menuBar.add(toolMenu);
    // setJMenuBar(menuBar);
    addHelpMenu("package.jmri.jmrit.operations.Operations_LocomotivesAdd", true); // NOI18N

    // get notified if combo box gets modified
    CarRoads.instance().addPropertyChangeListener(this);
    engineModels.addPropertyChangeListener(this);
    engineTypes.addPropertyChangeListener(this);
    engineLengths.addPropertyChangeListener(this);
    CarOwners.instance().addPropertyChangeListener(this);
    locationManager.addPropertyChangeListener(this);
    manager.addPropertyChangeListener(this);

    pack();
    setMinimumSize(new Dimension(Control.panelWidth500, Control.panelHeight500));
    setVisible(true);
  }

  public void loadEngine(Engine engine) {
    _engine = engine;

    if (!CarRoads.instance().containsName(engine.getRoadName())) {
      String msg =
          MessageFormat.format(
              Bundle.getMessage("roadNameNotExist"), new Object[] {engine.getRoadName()});
      if (JOptionPane.showConfirmDialog(
              this, msg, Bundle.getMessage("engineAddRoad"), JOptionPane.YES_NO_OPTION)
          == JOptionPane.YES_OPTION) {
        CarRoads.instance().addName(engine.getRoadName());
      }
    }
    roadComboBox.setSelectedItem(engine.getRoadName());

    roadNumberTextField.setText(engine.getNumber());

    if (!engineModels.containsName(engine.getModel())) {
      String msg =
          MessageFormat.format(
              Bundle.getMessage("modelNameNotExist"), new Object[] {engine.getModel()});
      if (JOptionPane.showConfirmDialog(
              this, msg, Bundle.getMessage("engineAddModel"), JOptionPane.YES_NO_OPTION)
          == JOptionPane.YES_OPTION) {
        engineModels.addName(engine.getModel());
      }
    }
    modelComboBox.setSelectedItem(engine.getModel());

    if (!engineTypes.containsName(engine.getTypeName())) {
      String msg =
          MessageFormat.format(
              Bundle.getMessage("typeNameNotExist"), new Object[] {engine.getTypeName()});
      if (JOptionPane.showConfirmDialog(
              this, msg, Bundle.getMessage("engineAddType"), JOptionPane.YES_NO_OPTION)
          == JOptionPane.YES_OPTION) {
        engineTypes.addName(engine.getTypeName());
      }
    }
    typeComboBox.setSelectedItem(engine.getTypeName());
    bUnitCheckBox.setSelected(engine.isBunit());

    if (!engineLengths.containsName(engine.getLength())) {
      String msg =
          MessageFormat.format(
              Bundle.getMessage("lengthNameNotExist"), new Object[] {engine.getLength()});
      if (JOptionPane.showConfirmDialog(
              this, msg, Bundle.getMessage("engineAddLength"), JOptionPane.YES_NO_OPTION)
          == JOptionPane.YES_OPTION) {
        engineLengths.addName(engine.getLength());
      }
    }
    lengthComboBox.setSelectedItem(engine.getLength());
    weightTextField.setText(engine.getWeightTons());
    hpTextField.setText(engine.getHp());

    locationBox.setSelectedItem(engine.getLocation());
    Location l = locationManager.getLocationById(engine.getLocationId());
    if (l != null) {
      l.updateComboBox(trackLocationBox);
      trackLocationBox.setSelectedItem(engine.getTrack());
    } else {
      trackLocationBox.removeAllItems();
    }

    builtTextField.setText(engine.getBuilt());

    if (!CarOwners.instance().containsName(engine.getOwner())) {
      String msg =
          MessageFormat.format(
              Bundle.getMessage("ownerNameNotExist"), new Object[] {engine.getOwner()});
      if (JOptionPane.showConfirmDialog(
              this, msg, Bundle.getMessage("addOwner"), JOptionPane.YES_NO_OPTION)
          == JOptionPane.YES_OPTION) {
        CarOwners.instance().addName(engine.getOwner());
      }
    }
    consistComboBox.setSelectedItem(engine.getConsistName());

    ownerComboBox.setSelectedItem(engine.getOwner());
    valueTextField.setText(engine.getValue());
    rfidComboBox.setSelectedItem(engine.getIdTag());
    commentTextField.setText(engine.getComment());

    setTitle(Bundle.getMessage("TitleEngineEdit"));
  }

  // combo boxes
  public void comboBoxActionPerformed(java.awt.event.ActionEvent ae) {
    if (ae.getSource() == modelComboBox) {
      if (modelComboBox.getSelectedItem() != null) {
        String model = (String) modelComboBox.getSelectedItem();
        // load the default hp and length for the model selected
        hpTextField.setText(engineModels.getModelHorsepower(model));
        weightTextField.setText(engineModels.getModelWeight(model));
        if (engineModels.getModelLength(model) != null
            && !engineModels.getModelLength(model).equals("")) {
          lengthComboBox.setSelectedItem(engineModels.getModelLength(model));
        }
        if (engineModels.getModelType(model) != null
            && !engineModels.getModelType(model).equals("")) {
          typeComboBox.setSelectedItem(engineModels.getModelType(model));
        }
      }
    }
    if (ae.getSource() == locationBox) {
      if (locationBox.getSelectedItem() == null) {
        trackLocationBox.removeAllItems();
      } else {
        log.debug("EnginesSetFrame sees location: " + locationBox.getSelectedItem());
        Location l = ((Location) locationBox.getSelectedItem());
        l.updateComboBox(trackLocationBox);
      }
    }
  }

  public void checkBoxActionPerformed(java.awt.event.ActionEvent ae) {
    JCheckBox b = (JCheckBox) ae.getSource();
    log.debug("checkbox change " + b.getText());
  }

  // Save, Delete, Add, Clear, Calculate buttons
  public void buttonActionPerformed(java.awt.event.ActionEvent ae) {
    if (ae.getSource() == saveButton) {
      // log.debug("engine save button activated");
      String roadNum = roadNumberTextField.getText();
      if (roadNum.length() > 10) {
        JOptionPane.showMessageDialog(
            this,
            Bundle.getMessage("engineRoadNum"),
            Bundle.getMessage("engineRoadLong"),
            JOptionPane.ERROR_MESSAGE);
        return;
      }
      // check to see if engine with road and number already exists
      Engine engine =
          manager.getByRoadAndNumber(
              (String) roadComboBox.getSelectedItem(), roadNumberTextField.getText());
      if (engine != null) {
        if (_engine == null || !engine.getId().equals(_engine.getId())) {
          JOptionPane.showMessageDialog(
              this,
              Bundle.getMessage("engineExists"),
              Bundle.getMessage("engineCanNotUpdate"),
              JOptionPane.ERROR_MESSAGE);
          return;
        }
      }

      // if the road or number changes, the loco needs a new id
      if (_engine != null
          && _engine.getRoadName() != null
          && !_engine.getRoadName().equals(Engine.NONE)
          && (!_engine.getRoadName().equals(roadComboBox.getSelectedItem())
              || !_engine.getNumber().equals(roadNumberTextField.getText()))) {
        String road = (String) roadComboBox.getSelectedItem();
        String number = roadNumberTextField.getText();
        manager.changeId(_engine, road, number);
        _engine.setRoadName(road);
        _engine.setNumber(number);
      }
      addEngine();
      /*
       * all JMRI window position and size are now saved // save frame
       * size and position manager.setEditFrame(this);
       */
      writeFiles();
      if (Setup.isCloseWindowOnSaveEnabled()) {
        dispose();
      }
    }
    if (ae.getSource() == deleteButton) {
      log.debug("engine delete button activated");
      if (_engine != null
          && _engine.getRoadName().equals(roadComboBox.getSelectedItem())
          && _engine.getNumber().equals(roadNumberTextField.getText())) {
        manager.deregister(_engine);
        _engine = null;
        // save engine file
        writeFiles();
      } else {
        Engine e =
            manager.getByRoadAndNumber(
                (String) roadComboBox.getSelectedItem(), roadNumberTextField.getText());
        if (e != null) {
          manager.deregister(e);
          // save engine file
          writeFiles();
        }
      }
    }
    if (ae.getSource() == addButton) {
      String roadNum = roadNumberTextField.getText();
      if (roadNum.length() > 10) {
        JOptionPane.showMessageDialog(
            this,
            Bundle.getMessage("engineRoadNum"),
            Bundle.getMessage("engineRoadLong"),
            JOptionPane.ERROR_MESSAGE);
        return;
      }
      Engine e =
          manager.getByRoadAndNumber(
              (String) roadComboBox.getSelectedItem(), roadNumberTextField.getText());
      if (e != null) {
        log.info("Can not add, engine already exists");
        JOptionPane.showMessageDialog(
            this,
            Bundle.getMessage("engineExists"),
            Bundle.getMessage("engineCanNotUpdate"),
            JOptionPane.ERROR_MESSAGE);
        return;
      }
      addEngine();
      // save engine file
      writeFiles();
    }
    if (ae.getSource() == clearRoadNumberButton) {
      roadNumberTextField.setText("");
      roadNumberTextField.requestFocus();
    }
  }

  private void addEngine() {
    if (roadComboBox.getSelectedItem() != null && !roadComboBox.getSelectedItem().equals("")) {
      if (_engine == null
          || !_engine.getRoadName().equals(roadComboBox.getSelectedItem())
          || !_engine.getNumber().equals(roadNumberTextField.getText())) {
        _engine =
            manager.newEngine(
                (String) roadComboBox.getSelectedItem(), roadNumberTextField.getText());
      }
      if (modelComboBox.getSelectedItem() != null) {
        _engine.setModel((String) modelComboBox.getSelectedItem());
      }
      if (typeComboBox.getSelectedItem() != null) {
        _engine.setTypeName((String) typeComboBox.getSelectedItem());
      }
      _engine.setBunit(bUnitCheckBox.isSelected());
      if (lengthComboBox.getSelectedItem() != null) {
        _engine.setLength((String) lengthComboBox.getSelectedItem());
      }
      _engine.setBuilt(builtTextField.getText());
      if (ownerComboBox.getSelectedItem() != null) {
        _engine.setOwner((String) ownerComboBox.getSelectedItem());
      }
      if (consistComboBox.getSelectedItem() != null) {
        if (consistComboBox.getSelectedItem().equals(EngineManager.NONE)) {
          _engine.setConsist(null);
          if (_engine.isBunit()) _engine.setBlocking(Engine.B_UNIT_BLOCKING);
          else _engine.setBlocking(Engine.DEFAULT_BLOCKING_ORDER);
        } else {
          _engine.setConsist(manager.getConsistByName((String) consistComboBox.getSelectedItem()));
          if (_engine.getConsist() != null) {
            _engine.setBlocking(_engine.getConsist().getSize());
          }
        }
      }
      // confirm that weight is a number
      if (!weightTextField.getText().equals("")) {
        try {
          Integer.parseInt(weightTextField.getText());
          _engine.setWeightTons(weightTextField.getText());
        } catch (Exception e) {
          JOptionPane.showMessageDialog(
              this,
              Bundle.getMessage("engineWeight"),
              Bundle.getMessage("engineCanNotWeight"),
              JOptionPane.ERROR_MESSAGE);
        }
      }
      // confirm that horsepower is a number
      if (!hpTextField.getText().equals("")) {
        try {
          Integer.parseInt(hpTextField.getText());
          _engine.setHp(hpTextField.getText());
        } catch (Exception e) {
          JOptionPane.showMessageDialog(
              this,
              Bundle.getMessage("engineHorsepower"),
              Bundle.getMessage("engineCanNotHp"),
              JOptionPane.ERROR_MESSAGE);
        }
      }
      if (locationBox.getSelectedItem() == null) {
        _engine.setLocation(null, null);
      } else {
        if (trackLocationBox.getSelectedItem() == null) {
          JOptionPane.showMessageDialog(
              this,
              Bundle.getMessage("rsFullySelect"),
              Bundle.getMessage("rsCanNotLoc"),
              JOptionPane.ERROR_MESSAGE);

        } else {
          String status =
              _engine.setLocation(
                  (Location) locationBox.getSelectedItem(),
                  (Track) trackLocationBox.getSelectedItem());
          if (!status.equals(Track.OKAY)) {
            log.debug("Can't set engine's location because of {}", status);
            JOptionPane.showMessageDialog(
                this,
                MessageFormat.format(
                    Bundle.getMessage("rsCanNotLocMsg"), new Object[] {_engine.toString(), status}),
                Bundle.getMessage("rsCanNotLoc"),
                JOptionPane.ERROR_MESSAGE);
            // does the user want to force the rolling stock to this track?
            int results =
                JOptionPane.showOptionDialog(
                    this,
                    MessageFormat.format(
                        Bundle.getMessage("rsForce"),
                        new Object[] {
                          _engine.toString(), (Track) trackLocationBox.getSelectedItem()
                        }),
                    MessageFormat.format(Bundle.getMessage("rsOverride"), new Object[] {status}),
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.QUESTION_MESSAGE,
                    null,
                    null,
                    null);
            if (results == JOptionPane.YES_OPTION) {
              log.debug("Force rolling stock to track");
              _engine.setLocation(
                  (Location) locationBox.getSelectedItem(),
                  (Track) trackLocationBox.getSelectedItem(),
                  true);
            }
          }
        }
      }
      _engine.setComment(commentTextField.getText());
      _engine.setValue(valueTextField.getText());
      _engine.setIdTag((IdTag) rfidComboBox.getSelectedItem());
    }
  }

  private void addEditButtonAction(JButton b) {
    b.addActionListener(
        new java.awt.event.ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent e) {
            buttonEditActionPerformed(e);
          }
        });
  }

  /**
   * Need to also write the location and train files if a road name was deleted. Need to also write
   * files if car type was changed.
   */
  private void writeFiles() {
    OperationsXml.save(); // save engine file
  }

  private boolean editActive = false;
  EngineAttributeEditFrame f;

  // edit buttons only one frame active at a time
  public void buttonEditActionPerformed(java.awt.event.ActionEvent ae) {
    if (editActive) {
      f.dispose();
    }
    f = new EngineAttributeEditFrame();
    f.setLocationRelativeTo(this);
    f.addPropertyChangeListener(this);
    editActive = true;

    if (ae.getSource() == editRoadButton) {
      f.initComponents(ROAD, (String) roadComboBox.getSelectedItem());
    }
    if (ae.getSource() == editModelButton) {
      f.initComponents(MODEL, (String) modelComboBox.getSelectedItem());
    }
    if (ae.getSource() == editTypeButton) {
      f.initComponents(TYPE, (String) typeComboBox.getSelectedItem());
    }
    if (ae.getSource() == editLengthButton) {
      f.initComponents(LENGTH, (String) lengthComboBox.getSelectedItem());
    }
    if (ae.getSource() == editOwnerButton) {
      f.initComponents(OWNER, (String) ownerComboBox.getSelectedItem());
    }
    if (ae.getSource() == editConsistButton) {
      f.initComponents(CONSIST, (String) consistComboBox.getSelectedItem());
    }
  }

  public void dispose() {
    removePropertyChangeListeners();
    super.dispose();
  }

  private void removePropertyChangeListeners() {
    CarRoads.instance().removePropertyChangeListener(this);
    engineModels.removePropertyChangeListener(this);
    engineTypes.removePropertyChangeListener(this);
    engineLengths.removePropertyChangeListener(this);
    CarOwners.instance().removePropertyChangeListener(this);
    locationManager.removePropertyChangeListener(this);
    manager.removePropertyChangeListener(this);
  }

  public void propertyChange(java.beans.PropertyChangeEvent e) {
    if (Control.showProperty) {
      log.debug(
          "Property change: ({}) old: ({}) new: ({})",
          e.getPropertyName(),
          e.getOldValue(),
          e.getNewValue());
    }
    if (e.getPropertyName().equals(CarRoads.CARROADS_CHANGED_PROPERTY)) {
      CarRoads.instance().updateComboBox(roadComboBox);
      if (_engine != null) {
        roadComboBox.setSelectedItem(_engine.getRoadName());
      }
    }
    if (e.getPropertyName().equals(EngineModels.ENGINEMODELS_CHANGED_PROPERTY)) {
      engineModels.updateComboBox(modelComboBox);
      if (_engine != null) {
        modelComboBox.setSelectedItem(_engine.getModel());
      }
    }
    if (e.getPropertyName().equals(EngineTypes.ENGINETYPES_CHANGED_PROPERTY)) {
      engineTypes.updateComboBox(typeComboBox);
      if (_engine != null) {
        typeComboBox.setSelectedItem(_engine.getTypeName());
      }
    }
    if (e.getPropertyName().equals(EngineLengths.ENGINELENGTHS_CHANGED_PROPERTY)) {
      engineLengths.updateComboBox(lengthComboBox);
      if (_engine != null) {
        lengthComboBox.setSelectedItem(_engine.getLength());
      }
    }
    if (e.getPropertyName().equals(EngineManager.CONSISTLISTLENGTH_CHANGED_PROPERTY)) {
      manager.updateConsistComboBox(consistComboBox);
      if (_engine != null) {
        consistComboBox.setSelectedItem(_engine.getConsistName());
      }
    }
    if (e.getPropertyName().equals(CarOwners.CAROWNERS_CHANGED_PROPERTY)) {
      CarOwners.instance().updateComboBox(ownerComboBox);
      if (_engine != null) {
        ownerComboBox.setSelectedItem(_engine.getOwner());
      }
    }
    if (e.getPropertyName().equals(LocationManager.LISTLENGTH_CHANGED_PROPERTY)) {
      LocationManager.instance().updateComboBox(locationBox);
      if (_engine != null) {
        locationBox.setSelectedItem(_engine.getLocation());
      }
    }
    if (e.getPropertyName().equals(EngineAttributeEditFrame.DISPOSE)) {
      editActive = false;
    }
  }

  private static final Logger log = LoggerFactory.getLogger(EngineEditFrame.class.getName());
}
예제 #11
0
파일: Car.java 프로젝트: JMRI/jmri-test
  /**
   * Construct this Entry from XML. This member has to remain synchronized with the detailed DTD in
   * operations-cars.dtd
   *
   * @param e Car XML element
   */
  public Car(org.jdom2.Element e) {
    super(e);
    loaded = true;
    org.jdom2.Attribute a;
    if ((a = e.getAttribute(Xml.PASSENGER)) != null) {
      _passenger = a.getValue().equals(Xml.TRUE);
    }
    if ((a = e.getAttribute(Xml.HAZARDOUS)) != null) {
      _hazardous = a.getValue().equals(Xml.TRUE);
    }
    if ((a = e.getAttribute(Xml.CABOOSE)) != null) {
      _caboose = a.getValue().equals(Xml.TRUE);
    }
    if ((a = e.getAttribute(Xml.FRED)) != null) {
      _fred = a.getValue().equals(Xml.TRUE);
    }
    if ((a = e.getAttribute(Xml.UTILITY)) != null) {
      _utility = a.getValue().equals(Xml.TRUE);
    }
    if ((a = e.getAttribute(Xml.KERNEL)) != null) {
      Kernel k = CarManager.instance().getKernelByName(a.getValue());
      if (k != null) {
        setKernel(k);
        if ((a = e.getAttribute(Xml.LEAD_KERNEL)) != null && a.getValue().equals(Xml.TRUE)) {
          _kernel.setLead(this);
        }
      } else {
        log.error("Kernel " + a.getValue() + " does not exist");
      }
    }
    if ((a = e.getAttribute(Xml.LOAD)) != null) {
      _loadName = a.getValue();
    }
    if ((a = e.getAttribute(Xml.LOAD_FROM_STAGING)) != null && a.getValue().equals(Xml.TRUE)) {
      setLoadGeneratedFromStaging(true);
    }

    if ((a = e.getAttribute(Xml.WAIT)) != null) {
      try {
        _wait = Integer.parseInt(a.getValue());
      } catch (NumberFormatException nfe) {
        log.error("Wait count ({}) for car ({}) isn't a valid number!", a.getValue(), toString());
      }
    }
    if ((a = e.getAttribute(Xml.PICKUP_SCHEDULE_ID)) != null) {
      _pickupScheduleId = a.getValue();
    }
    if ((a = e.getAttribute(Xml.SCHEDULE_ID)) != null) {
      _scheduleId = a.getValue();
    }
    if ((a = e.getAttribute(Xml.NEXT_LOAD)) != null) {
      _nextLoadName = a.getValue();
    }
    if ((a = e.getAttribute(Xml.NEXT_WAIT)) != null) {
      try {
        _nextWait = Integer.parseInt(a.getValue());
      } catch (NumberFormatException nfe) {
        log.error(
            "Next wait count ({}) for car ({}) isn't a valid number!", a.getValue(), toString());
      }
    }
    if ((a = e.getAttribute(Xml.NEXT_PICKUP_SCHEDULE_ID)) != null) {
      _nextPickupScheduleId = a.getValue();
    }
    if ((a = e.getAttribute(Xml.NEXT_DEST_ID)) != null) {
      setFinalDestination(LocationManager.instance().getLocationById(a.getValue()));
    }
    if (getFinalDestination() != null && (a = e.getAttribute(Xml.NEXT_DEST_TRACK_ID)) != null) {
      setFinalDestinationTrack(getFinalDestination().getTrackById(a.getValue()));
    }
    if ((a = e.getAttribute(Xml.PREVIOUS_NEXT_DEST_ID)) != null) {
      setPreviousFinalDestination(LocationManager.instance().getLocationById(a.getValue()));
    }
    if (getPreviousFinalDestination() != null
        && (a = e.getAttribute(Xml.PREVIOUS_NEXT_DEST_TRACK_ID)) != null) {
      setPreviousFinalDestinationTrack(getPreviousFinalDestination().getTrackById(a.getValue()));
    }
    if ((a = e.getAttribute(Xml.PREVIOUS_SCHEDULE_ID)) != null) {
      setPreviousScheduleId(a.getValue());
    }
    if ((a = e.getAttribute(Xml.RWE_DEST_ID)) != null) {
      _rweDestination = LocationManager.instance().getLocationById(a.getValue());
    }
    if (_rweDestination != null && (a = e.getAttribute(Xml.RWE_DEST_TRACK_ID)) != null) {
      _rweDestTrack = _rweDestination.getTrackById(a.getValue());
    }
    if ((a = e.getAttribute(Xml.RWE_LOAD)) != null) {
      _rweLoadName = a.getValue();
    }
    addPropertyChangeListeners();
  }
예제 #12
0
/**
 * Frame for copying a location for operations.
 *
 * @author Bob Jacobsen Copyright (C) 2001
 * @author Daniel Boudreau Copyright (C) 2014
 * @version $Revision: 17977 $
 */
public class LocationCopyFrame extends OperationsFrame
    implements java.beans.PropertyChangeListener {

  LocationManager locationManager = LocationManager.instance();

  // text field
  JTextField loctionNameTextField =
      new javax.swing.JTextField(Control.max_len_string_location_name);

  // major buttons
  JButton copyButton = new javax.swing.JButton(Bundle.getMessage("Copy"));
  JButton saveButton = new javax.swing.JButton(Bundle.getMessage("Save"));

  // combo boxes
  JComboBox<Location> locationBox = locationManager.getComboBox();

  // checkboxes
  JCheckBox moveRollingStockCheckBox = new JCheckBox(Bundle.getMessage("MoveRollingStock"));
  JCheckBox deleteTrackCheckBox = new JCheckBox(Bundle.getMessage("DeleteCopiedTrack"));

  // remember state of checkboxes during a session
  static boolean moveRollingStock = false;
  static boolean deleteTrack = false;

  public LocationCopyFrame() {

    // general GUI config
    getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

    // Set up the panels
    // Layout the panel by rows
    // row 1
    JPanel pName = new JPanel();
    pName.setLayout(new GridBagLayout());
    pName.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("LocationName")));
    addItem(pName, loctionNameTextField, 0, 0);

    // row 2
    JPanel pCopy = new JPanel();
    pCopy.setLayout(new GridBagLayout());
    pCopy.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("SelectLocationToCopy")));
    addItem(pCopy, locationBox, 0, 0);

    // row 3
    JPanel pOptions = new JPanel();
    pOptions.setLayout(new GridBagLayout());
    pOptions.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("Options")));
    addItemLeft(pOptions, moveRollingStockCheckBox, 0, 1);
    addItemLeft(pOptions, deleteTrackCheckBox, 0, 2);

    // row 4
    JPanel pButton = new JPanel();
    pButton.setLayout(new GridBagLayout());
    addItem(pButton, copyButton, 0, 0);
    addItem(pButton, saveButton, 1, 0);

    getContentPane().add(pName);
    getContentPane().add(pCopy);
    getContentPane().add(pOptions);
    getContentPane().add(pButton);

    // set the checkbox states
    moveRollingStockCheckBox.setSelected(moveRollingStock);
    deleteTrackCheckBox.setSelected(deleteTrack);
    deleteTrackCheckBox.setEnabled(moveRollingStockCheckBox.isSelected());

    // get notified if combo box gets modified
    locationManager.addPropertyChangeListener(this);

    // add help menu to window
    addHelpMenu("package.jmri.jmrit.operations.Operations_CopyLocation", true); // NOI18N

    pack();
    setMinimumSize(new Dimension(Control.panelWidth400, Control.panelHeight400));

    // setup buttons
    addButtonAction(copyButton);
    addButtonAction(saveButton);

    addCheckBoxAction(moveRollingStockCheckBox);

    setTitle(Bundle.getMessage("MenuItemCopyLocation"));
  }

  @Override
  @edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
      value = "ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD",
      justification = "GUI ease of use")
  protected void buttonActionPerformed(java.awt.event.ActionEvent ae) {
    if (ae.getSource() == copyButton) {
      log.debug("copy location button activated");
      if (!checkName()) {
        return;
      }

      if (locationBox.getSelectedItem() == null) {
        JOptionPane.showMessageDialog(
            this,
            Bundle.getMessage("SelectLocationToCopy"),
            MessageFormat.format(
                Bundle.getMessage("CanNotLocation"), new Object[] {Bundle.getMessage("Copy")}),
            JOptionPane.ERROR_MESSAGE);
        return;
      }

      Location location = (Location) locationBox.getSelectedItem();
      // check to see if there are cars scheduled for pickup or set out
      if (moveRollingStockCheckBox.isSelected()) {
        for (Track track : location.getTrackList()) {
          if (track.getPickupRS() > 0) {
            JOptionPane.showMessageDialog(
                this,
                MessageFormat.format(
                    Bundle.getMessage("FoundRollingStockPickUp"),
                    new Object[] {track.getPickupRS()}),
                MessageFormat.format(
                    Bundle.getMessage("TrainsServicingTrack"), new Object[] {track.getName()}),
                JOptionPane.WARNING_MESSAGE);
            return; // can't move rolling stock, some are scheduled for a pick up
          }
          if (track.getDropRS() > 0) {
            JOptionPane.showMessageDialog(
                this,
                MessageFormat.format(
                    Bundle.getMessage("FoundRollingStockDrop"), new Object[] {track.getDropRS()}),
                MessageFormat.format(
                    Bundle.getMessage("TrainsServicingTrack"), new Object[] {track.getName()}),
                JOptionPane.WARNING_MESSAGE);
            return; // can't move rolling stock, some are scheduled for drops
          }
        }
      }
      // now copy all of the tracks
      Location newLocation = locationManager.newLocation(loctionNameTextField.getText());
      location.copyLocation(newLocation);

      // does the user want the cars to also move to the new tracks?
      if (moveRollingStockCheckBox.isSelected()) {
        for (Track track : location.getTrackList()) {
          moveRollingStock(track, newLocation.getTrackByName(track.getName(), null));
          if (deleteTrackCheckBox.isSelected()) {
            location.deleteTrack(track);
          }
        }
      }
    }
    if (ae.getSource() == saveButton) {
      log.debug("save track button activated");
      // save checkbox states
      moveRollingStock = moveRollingStockCheckBox.isSelected();
      deleteTrack = deleteTrackCheckBox.isSelected();
      // save location file
      OperationsXml.save();
    }
  }

  @Override
  protected void checkBoxActionPerformed(java.awt.event.ActionEvent ae) {
    if (ae.getSource() == moveRollingStockCheckBox) {
      deleteTrackCheckBox.setEnabled(moveRollingStockCheckBox.isSelected());
      deleteTrackCheckBox.setSelected(false);
    }
  }

  protected void updateComboBoxes() {
    log.debug("update location combobox");
    Object item = locationBox.getSelectedItem(); // remember which object was selected
    locationManager.updateComboBox(locationBox);
    locationBox.setSelectedItem(item);
  }

  /** @return true if name entered OK and isn't too long */
  protected boolean checkName() {
    if (loctionNameTextField.getText().trim().equals("")) {
      JOptionPane.showMessageDialog(
          this,
          Bundle.getMessage("MustEnterName"),
          MessageFormat.format(
              Bundle.getMessage("CanNotLocation"), new Object[] {Bundle.getMessage("Copy")}),
          JOptionPane.ERROR_MESSAGE);
      return false;
    }
    if (TrainCommon.splitString(loctionNameTextField.getText()).length()
        > Control.max_len_string_location_name) {
      JOptionPane.showMessageDialog(
          this,
          MessageFormat.format(
              Bundle.getMessage("LocationNameLengthMax"),
              new Object[] {Integer.toString(Control.max_len_string_location_name + 1)}),
          MessageFormat.format(
              Bundle.getMessage("CanNotLocation"), new Object[] {Bundle.getMessage("Copy")}),
          JOptionPane.ERROR_MESSAGE);
      return false;
    }
    Location check = locationManager.getLocationByName(loctionNameTextField.getText());
    if (check != null) {
      JOptionPane.showMessageDialog(
          this,
          Bundle.getMessage("LocationAlreadyExists"),
          MessageFormat.format(
              Bundle.getMessage("CanNotLocation"), new Object[] {Bundle.getMessage("Copy")}),
          JOptionPane.ERROR_MESSAGE);
      return false;
    }
    return true;
  }

  protected void moveRollingStock(Track fromTrack, Track toTrack) {
    moveRollingStock(fromTrack, toTrack, CarManager.instance());
    moveRollingStock(fromTrack, toTrack, EngineManager.instance());
  }

  private void moveRollingStock(Track fromTrack, Track toTrack, RollingStockManager manager) {
    for (RollingStock rs : manager.getByIdList()) {
      if (rs.getTrack() == fromTrack) {
        rs.setLocation(toTrack.getLocation(), toTrack, RollingStock.FORCE);
      }
    }
  }

  @Override
  public void dispose() {
    locationManager.removePropertyChangeListener(this);
    super.dispose();
  }

  @Override
  public void propertyChange(java.beans.PropertyChangeEvent e) {
    log.debug("PropertyChange ({}) new: ({})", e.getPropertyName(), e.getNewValue());
    if (e.getPropertyName().equals(LocationManager.LISTLENGTH_CHANGED_PROPERTY)) {
      updateComboBoxes();
    }
  }

  private static final Logger log = LoggerFactory.getLogger(LocationCopyFrame.class.getName());
}