Warning: Can't use blame annotator:
svn blame failed on trunk/src/tmcsim/client/cadclientgui/screens/AssignedIncidents.java: ("Can't find a temporary directory: Internal error", 20014)

source: tmcsimulator/trunk/src/tmcsim/client/cadclientgui/screens/AssignedIncidents.java @ 445

Revision 445, 22.0 KB checked in by jdalbey, 7 years ago (diff)

Changed restart dialog in CADClientView to a non-modal one to fix #159. Shortened exception log messages in other client modules.

RevLine 
1package tmcsim.client.cadclientgui.screens;
2
3import java.awt.Color;
4import java.awt.Component;
5import java.awt.Dimension;
6import java.awt.Point;
7import java.awt.Toolkit;
8import java.awt.datatransfer.DataFlavor;
9import java.awt.datatransfer.Transferable;
10import java.awt.event.ComponentEvent;
11import java.awt.event.ComponentListener;
12import java.awt.event.MouseEvent;
13import java.awt.event.MouseListener;
14import java.awt.event.MouseMotionListener;
15import java.rmi.RemoteException;
16import java.util.List;
17import java.util.logging.Level;
18import java.util.logging.Logger;
19import javax.swing.Box;
20import javax.swing.BoxLayout;
21import javax.swing.JFrame;
22import javax.swing.JLabel;
23import javax.swing.JScrollPane;
24import javax.swing.JSeparator;
25import javax.swing.JTable;
26import javax.swing.ListSelectionModel;
27import javax.swing.RowSorter.SortKey;
28import javax.swing.SwingUtilities;
29import javax.swing.TransferHandler;
30import javax.swing.table.DefaultTableModel;
31import javax.swing.table.TableCellRenderer;
32import tmcsim.client.cadclientgui.enums.CADDataEnums;
33import tmcsim.client.cadclientgui.enums.CADScriptTags.UNIT_TAGS;
34import tmcsim.client.cadclientgui.enums.IncidentEnums;
35import tmcsim.client.cadclientgui.enums.TableHeaders;
36import tmcsim.client.cadclientgui.enums.UnitStatusEnums;
37
38/**
39 * This class contains the view and controller for the AssignedIncidents screen.
40 * The view was not built using a GUI builder plug-in (but may want to consider
41 * doing so in the future), and the controller uses listeners to control how the
42 * view and data act.
43 *
44 * @author Vincent
45 */
46public class AssignedIncidents extends JFrame
47{
48    private final String SCREEN_TITLE = "(Shift + F3)  Assigned Incidents";
49    private final Dimension SCREEN_DIMENSIONS = new Dimension(1400, 250);
50    private final Dimension DROP_DOWN_MENU_LABEL_DIMENSIONS = new Dimension(
51            170, 20);
52    private final Dimension DROP_DOWN_MENU_DIMENSIONS = new Dimension(170, 230);
53    private final int COLUMN_WIDTH = 120;
54    private final String[] LABELS =
55    {
56        "Add Resources...", "Greater Alarm...",
57        "Reconfigure", "Open", "Recall Incident", "Cancel", "Reassign",
58        "Link/Append", "Map", "Recall Linked Incidents", "Read Notes",
59        "Page...", "Mail...", "Fax..."
60    };
61    private final String LABEL_SPACING = "     ";
62    private JTable assignedIncidentsTable;
63    private JFrame assignedIncidentsMenu;
64    // labels for the drop down menu
65    private JLabel[] dropDownLabels = new JLabel[LABELS.length];
66    private static Logger clientLogger = Logger.getLogger("tmcsim.client");
67    private long lastLeftClick;// used for double clicking feature
68
69    public AssignedIncidents()
70    {
71        initComponents();
72    }
73
74    private void initComponents()
75    {
76        initializeTable();
77        initController();
78        initializeDropDownMenu();
79
80        JScrollPane scrollpane = new JScrollPane(assignedIncidentsTable);
81        scrollpane.getViewport().setBackground(Color.WHITE);
82
83        setTitle(SCREEN_TITLE);
84        setPreferredSize(SCREEN_DIMENSIONS);
85        getContentPane().add(scrollpane);
86        setResizable(true);
87        pack();
88        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
89        setLocation(0, (int) (dim.getHeight() / 4));
90        setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
91        setVisible(false);
92    }
93
94    /*
95     * Initializes the table and prepares the cell renderer for color
96     * management. It initializes the default settings and handles the drag and
97     * drop feature.
98     */
99    private void initializeTable()
100    {
101        assignedIncidentsTable = new JTable()
102        {
103            /*
104             * Custom renderer to set different background/foreground colors
105             * @see javax.swing.JTable#prepareRenderer(javax.swing.table.TableCellRenderer, int, int)
106             */
107            public Component prepareRenderer(TableCellRenderer renderer, int row, int column)
108            {
109                Component comp;
110                // In a rare odd circumstance of timing, this exception is thrown:
111                // http://pastebin.com/A3tZe07a
112                try
113                {
114                    comp = super.prepareRenderer(renderer, row, column);
115                } catch (Exception ex)
116                {
117                    clientLogger.logp(Level.INFO, "AssignedIncidents",
118                            "prepareRenderer", "row=" + row + " col=" + column, ex);
119
120                    // Our workaround is to just return a dummy value.
121                    // It will be erased in the next one second refresh
122                    return new JLabel("?");
123                }
124
125                comp.setForeground(Color.BLACK);
126                comp.setBackground(Color.CYAN);
127                if (assignedIncidentsTable.getModel().getColumnName(column).equals("Unit/s"))
128                {//4 is the column for "Unit/s"
129                    //System.out.println("Diagnostic: in AssignedIncidents.prepareRenderer()"); //Commenting this line breaks the client
130                    comp.setBackground(Color.BLACK);
131                    int primaryColumn = 3;
132                    try
133                    {
134                        // get the unit name from the table   JD
135                        String unitname = (String) assignedIncidentsTable.getValueAt(row, primaryColumn);
136                        // Validate that unitname isn't blank
137                        if (!unitname.equals(""))
138                        {
139                            // Fetch the unit's current status from server
140                            UnitStatusEnums ustatus = ScreenManager.theCoordinator.getCadDataUnitStatus(unitname);
141                            // Ad-hoc incidents don't have a status so use WHITE
142                            comp.setForeground(Color.WHITE);
143                            // Decide which color to use for displaying the status
144                            switch (ustatus)
145                            {
146                                case Assignable:
147                                    comp.setForeground(Color.GREEN);
148                                    break;
149                                case Arrived:
150                                    comp.setForeground(Color.YELLOW);
151                                    break;
152                                case Enroute:
153                                    comp.setForeground(Color.CYAN);
154                                    break;
155                            }
156                        }
157                    } catch (RemoteException e)
158                    {
159                        e.printStackTrace();
160                    }
161                }
162
163                if (getSelectedRow() == row)
164                {
165                    comp.setForeground(Color.WHITE);
166                    comp.setBackground(Color.BLUE);
167                }
168
169                return comp;
170            }
171
172            public Class getColumnClass(int c)
173            {
174                return getValueAt(0, c).getClass();
175            }
176        };
177        // Use a custom renderer to resolve ticket #78
178        assignedIncidentsTable.setDefaultRenderer(Integer.class, new IncidentNumberRenderer());
179
180        assignedIncidentsTable.setOpaque(true);
181        assignedIncidentsTable.setIntercellSpacing(new Dimension(1, 0));
182        assignedIncidentsTable.setGridColor(Color.WHITE);
183        assignedIncidentsTable.getTableHeader().setReorderingAllowed(false);
184        assignedIncidentsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
185        assignedIncidentsTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
186        assignedIncidentsTable.setAutoCreateRowSorter(true);
187        assignedIncidentsTable.setModel(new DefaultTableModel());
188
189        ((DefaultTableModel) assignedIncidentsTable.getModel()).setColumnIdentifiers(TableHeaders.ASSIGNED_INCIDENTS_HEADERS);
190
191        assignedIncidentsTable.setTransferHandler(new TransferHandler()
192        {
193            public boolean canImport(TransferHandler.TransferSupport info)
194            {
195                // Check for String flavor
196                if (!info.isDataFlavorSupported(DataFlavor.stringFlavor))
197                {
198                    return false;
199                }
200                return true;
201            }
202
203            public boolean importData(TransferHandler.TransferSupport info)
204            {
205                if (!info.isDrop())
206                {
207                    return false;
208                }
209
210                DefaultTableModel tableModel = (DefaultTableModel) assignedIncidentsTable.getModel();
211                JTable.DropLocation dl = (JTable.DropLocation) info.getDropLocation();
212                int index = dl.getRow();
213
214                // Get the string that is being dropped.
215                Transferable t = info.getTransferable();
216                String data;
217                try
218                {
219                    data = (String) t.getTransferData(DataFlavor.stringFlavor);
220                } catch (Exception e)
221                {
222                    return false;
223                }
224
225                // Perform the actual import
226                int incidentId = (Integer) assignedIncidentsTable.getValueAt(dl.getRow(), 0);
227                try
228                {
229                    ScreenManager.theCoordinator.setCadDataUnitAssignedId(data, incidentId);
230                    ScreenManager.theCoordinator.setCadDataUnitValue(data,
231                            UNIT_TAGS.UNIT_STATUS, UnitStatusEnums.Arrived);
232                    ScreenManager.theCoordinator.addCadDataIncidentAssignedUnitNum(incidentId, data);
233                    ScreenManager.theCoordinator.setCadDataIncidentStatus(incidentId, IncidentEnums.Assigned);
234                } catch (RemoteException e)
235                {
236                    e.printStackTrace();
237                }
238                ScreenManager.refreshScreens();
239                return true;
240            }
241        });
242
243        for (int i = 0; i < assignedIncidentsTable.getColumnCount(); i++)
244        {
245            assignedIncidentsTable.getColumnModel().getColumn(i).setPreferredWidth(120);
246        }
247    }
248
249    /*
250     * Adds the key and mouse listeners for the table and component listener for
251     * screen.
252     */
253    private void initController()
254    {
255        assignedIncidentsTable.addMouseListener(new MouseListener()
256        {
257            public void mouseClicked(MouseEvent e)
258            {
259                if (SwingUtilities.isLeftMouseButton(e))
260                {
261                    // TODO:  Use e.getClickCount() == 2
262                    if (System.currentTimeMillis() - lastLeftClick < 1000)
263                    {
264                        int idColumn = 0;
265                        int selectedRow = assignedIncidentsTable.getSelectedRow();
266                        try
267                        {
268                            int selectedValue = (Integer) assignedIncidentsTable.getValueAt(selectedRow, idColumn);
269                            ScreenManager.openIncidentViewer(selectedValue);
270                        } catch (IndexOutOfBoundsException ex)
271                        {
272                            ex.printStackTrace();
273                        }
274                    }
275                    else
276                    {
277                        lastLeftClick = System.currentTimeMillis();
278                    }
279                }
280                if (SwingUtilities.isRightMouseButton(e))
281                {
282                    // Fixed to force right click to cause the row to be selected. JD
283                    // get the coordinates of the mouse click
284                    Point p = e.getPoint();
285                    // get the row index that contains that coordinate
286                    int rowNumber = assignedIncidentsTable.rowAtPoint(p);
287                    // Get the ListSelectionModel of the JTable
288                    ListSelectionModel model = assignedIncidentsTable.getSelectionModel();
289                    // set the selected interval of rows. Using the "rowNumber"
290                    // variable for the beginning and end selects only that one row.
291                    model.setSelectionInterval(rowNumber, rowNumber);
292                    // go open the drop down menu
293                    openDropDownMenu(e);
294                }
295                else
296                {
297                    closeDropDownMenu();
298                }
299            }
300
301            public void mouseEntered(MouseEvent e)
302            {
303            }
304
305            public void mouseExited(MouseEvent e)
306            {
307            }
308
309            public void mousePressed(MouseEvent e)
310            {
311            }
312
313            public void mouseReleased(MouseEvent e)
314            {
315            }
316        });
317
318        addComponentListener(new ComponentListener()
319        {
320            public void componentHidden(ComponentEvent e)
321            {
322            }
323
324            public void componentMoved(ComponentEvent e)
325            {
326                closeDropDownMenu();
327            }
328
329            public void componentResized(ComponentEvent e)
330            {
331            }
332
333            public void componentShown(ComponentEvent e)
334            {
335            }
336        });
337    }
338
339    /*
340     * Creates the drop down menu that appears when a right click is performed
341     * on the table.
342     */
343    private void initializeDropDownMenu()
344    {
345        Box menu = new Box(BoxLayout.Y_AXIS);
346        initializeDropDownLabels();
347        addLabelsToBox(menu);
348
349        // Sets the highlighted background color, note that it does not become
350        // "Highlighted" until opaque(true) is called
351        setMenuHighlightedBackground(Color.BLUE);
352
353        assignedIncidentsMenu = new JFrame();
354        assignedIncidentsMenu.getContentPane().add(menu);
355        assignedIncidentsMenu.setPreferredSize(DROP_DOWN_MENU_DIMENSIONS);
356        assignedIncidentsMenu.setUndecorated(true);
357        assignedIncidentsMenu.pack();
358        assignedIncidentsMenu.setVisible(false);
359    }
360
361    /*
362     * Sets the text and size and adds a listener to each activated label.
363     */
364    private void initializeDropDownLabels()
365    {
366        for (int i = 0; i < dropDownLabels.length; i++)
367        {
368            dropDownLabels[i] = new JLabel(LABEL_SPACING + LABELS[i]);
369            dropDownLabels[i].setMaximumSize(DROP_DOWN_MENU_LABEL_DIMENSIONS);
370            dropDownLabels[i].setForeground(Color.GRAY);
371        }
372        dropDownLabels[3].setForeground(Color.BLACK);
373        addMouseListenersToLabel(dropDownLabels[3]);
374        dropDownLabels[10].setForeground(Color.BLACK);
375        addMouseListenersToLabel(dropDownLabels[10]);
376    }
377
378    /*
379     * Add the labels to the box in order with separators and spacings in
380     * between.
381     */
382    private void addLabelsToBox(Box menu)
383    {
384        menu.add(dropDownLabels[0]);
385        menu.add(dropDownLabels[1]);
386        menu.add(dropDownLabels[2]);
387
388        menu.add(Box.createVerticalStrut(5));
389        menu.add(new JSeparator());
390        menu.add(Box.createVerticalStrut(5));
391
392        menu.add(dropDownLabels[3]);
393        menu.add(dropDownLabels[4]);
394        menu.add(dropDownLabels[5]);
395        menu.add(dropDownLabels[6]);
396        menu.add(dropDownLabels[7]);
397
398        menu.add(Box.createVerticalStrut(5));
399        menu.add(new JSeparator());
400        menu.add(Box.createVerticalStrut(5));
401
402        menu.add(dropDownLabels[8]);
403        menu.add(dropDownLabels[9]);
404        menu.add(dropDownLabels[10]);
405
406        menu.add(Box.createVerticalStrut(5));
407        menu.add(new JSeparator());
408        menu.add(Box.createVerticalStrut(5));
409
410        menu.add(dropDownLabels[11]);
411        menu.add(dropDownLabels[12]);
412        menu.add(dropDownLabels[13]);
413
414        menu.add(Box.createVerticalStrut(5));
415    }
416
417    /*
418     * Sets the highlighted color(when the mouse is over it) of the JLabels.
419     * Note: the color is not shown until .setOpaque(true) is called.
420     *
421     * @param color the highlighted color
422     */
423    public void setMenuHighlightedBackground(Color color)
424    {
425        for (int i = 0; i < dropDownLabels.length; i++)
426        {
427            dropDownLabels[i].setBackground(color);
428        }
429    }
430
431    /*
432     * Sets all JLabels to not display a highlighted background
433     */
434    public void unSelectAllLabels()
435    {
436        for (int i = 0; i < dropDownLabels.length; i++)
437        {
438            dropDownLabels[i].setOpaque(false);
439        }
440    }
441
442    /*
443     * Sets the label to have a highlighted background.
444     *
445     * @param label the label that is selected/highlighted
446     */
447    public void selectLabel(Object label)
448    {
449        ((JLabel) label).setOpaque(true);
450    }
451
452    /*
453     * Performs the label action depending on which label was clicked.
454     */
455    public void performLabelAction(Object label)
456    {
457        if (label.equals(dropDownLabels[0]))
458        {// Add Resources
459        }
460        else if (label.equals(dropDownLabels[1]))
461        {// Greater Alarm
462        }
463        else if (label.equals(dropDownLabels[2]))
464        {// Reconfigure
465        }
466        else if (label.equals(dropDownLabels[3]))
467        {// Open
468            int idColumn = 0;
469            int selectedRow = assignedIncidentsTable.getSelectedRow();
470            try
471            {
472                int selectedValue = (Integer) assignedIncidentsTable.getValueAt(selectedRow, idColumn);
473                ScreenManager.openIncidentViewer(selectedValue);
474            } catch (IndexOutOfBoundsException ex)
475            {
476                ex.printStackTrace();
477            }
478        }
479        else if (label.equals(dropDownLabels[4]))
480        {// Recall Incident
481        }
482        else if (label.equals(dropDownLabels[5]))
483        {// Cancel
484        }
485        else if (label.equals(dropDownLabels[6]))
486        {// Reassign
487        }
488        else if (label.equals(dropDownLabels[7]))
489        {// Link append
490        }
491        else if (label.equals(dropDownLabels[8]))
492        {// Map
493        }
494        else if (label.equals(dropDownLabels[9]))
495        {// Recall Linked Incidents
496        }
497        else if (label.equals(dropDownLabels[10]))
498        {// Read Notes
499            int idColumn = 0;
500            ScreenManager.openIncidentViewer((Integer) assignedIncidentsTable
501                    .getValueAt(assignedIncidentsTable.getSelectedRow(),
502                    idColumn));
503        }
504        else if (label.equals(dropDownLabels[11]))
505        {// Page
506        }
507        else if (label.equals(dropDownLabels[12]))
508        {// Mail
509        }
510        else if (label.equals(dropDownLabels[13]))
511        {// Fax
512        }
513    }
514
515    /*
516     * Factory method. Adds a mouse listeners to the label. The
517     * MouseMotionListener detects the mouse's location to highlight the label.
518     * The MouseListener detects for clicks and performs the action of the label
519     * designates.
520     */
521    public void addMouseListenersToLabel(JLabel label)
522    {
523        label.addMouseMotionListener(new MouseMotionListener()
524        {
525            public void mouseDragged(MouseEvent e)
526            {
527            }
528
529            public void mouseMoved(MouseEvent e)
530            {
531                unSelectAllLabels();
532                selectLabel(e.getSource());
533                assignedIncidentsMenu.revalidate();
534                assignedIncidentsMenu.repaint();
535            }
536        });
537        label.addMouseListener(new MouseListener()
538        {
539            public void mouseClicked(MouseEvent e)
540            {
541                performLabelAction(e.getSource());
542                unSelectAllLabels();
543                assignedIncidentsMenu.revalidate();
544                assignedIncidentsMenu.repaint();
545                assignedIncidentsMenu.setVisible(false);
546            }
547
548            public void mouseEntered(MouseEvent e)
549            {
550            }
551
552            public void mouseExited(MouseEvent e)
553            {
554            }
555
556            public void mousePressed(MouseEvent e)
557            {
558            }
559
560            public void mouseReleased(MouseEvent e)
561            {
562            }
563        });
564    }
565
566    /*
567     * Displays the menu where the right click occurred.
568     */
569    public void openDropDownMenu(MouseEvent e)
570    {
571        assignedIncidentsMenu.setLocation(e.getX() + this.getX(), e.getY()
572                + this.getY());
573        assignedIncidentsMenu.setVisible(true);
574    }
575
576    /*
577     * Hides the menu.
578     */
579    public void closeDropDownMenu()
580    {
581        unSelectAllLabels();
582        assignedIncidentsMenu.revalidate();
583        assignedIncidentsMenu.repaint();
584        assignedIncidentsMenu.setVisible(false);
585    }
586
587    /*
588     * Refreshes the data in the table by updating all data and repainting the
589     * screen. It saves user preferences(like column sizes, selected row, sorted preferences)
590     * and applies them to the updated model it receives from the server.
591     */
592    public void refreshTable()
593    {
594
595        if (assignedIncidentsTable.getTableHeader().getResizingColumn() == null)
596        {//only update info if resize not in progress
597            try
598            {
599                int index = assignedIncidentsTable.getSelectedRow();
600                int[] columnWidths = new int[20];
601                List<? extends SortKey> keys = assignedIncidentsTable.getRowSorter().getSortKeys();
602                for (int i = 0; i < assignedIncidentsTable.getColumnCount(); i++)
603                {
604                    columnWidths[i] = assignedIncidentsTable.getColumnModel().getColumn(i).getWidth();
605                }
606
607                assignedIncidentsTable.setModel(ScreenManager.theCoordinator.getCadDataTable(CADDataEnums.TABLE.ASSIGNED_INCIDENTS));
608
609                for (int i = 0; i < assignedIncidentsTable.getColumnCount(); i++)
610                {
611                    assignedIncidentsTable.getColumnModel().getColumn(i).setPreferredWidth(columnWidths[i]);
612                }
613                assignedIncidentsTable.getRowSorter().setSortKeys(keys);
614                assignedIncidentsTable.getSelectionModel().setSelectionInterval(index, index);
615            } catch (RemoteException ex)
616            {
617                System.out.println("RemoteException in refreshTable method of AssignedIncidents.java");
618                System.out.println(ex.getMessage());
619            }
620            revalidate();
621            repaint();
622        }
623    }
624
625    /*
626     * Makes screen visible.
627     */
628    public void open()
629    {
630        setVisible(true);
631    }
632
633    /*
634     * Hides screen.
635     */
636    public void close()
637    {
638        setVisible(false);
639    }
640}
Note: See TracBrowser for help on using the repository browser.