/
SwitchboardEditor.java
1392 lines (1281 loc) · 52.3 KB
/
SwitchboardEditor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package jmri.jmrit.display.switchboardEditor;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.SpinnerNumberModel;
import javax.swing.WindowConstants;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import jmri.ConfigureManager;
import jmri.InstanceManager;
import jmri.Manager;
import jmri.NamedBean;
import jmri.NamedBeanUsageReport;
import jmri.jmrit.display.CoordinateEdit;
import jmri.jmrit.display.Editor;
import jmri.jmrit.display.Positionable;
import jmri.jmrit.display.PositionableJComponent;
import jmri.jmrit.display.ToolTip;
import jmri.util.ColorUtil;
import jmri.util.JmriJFrame;
import jmri.util.swing.JmriColorChooser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Provides a simple editor for adding jmri.jmrit.display.switchBoard items to a
* JLayeredPane inside a captive JFrame. Primary use is for new users.
* <p>
* GUI is structured as a separate setup panel to set the visible range and type
* plus menus.
* <p>
* All created objects are put insite a GridLayout grid. No special use of the
* LayeredPane layers. Inspired by Oracle JLayeredPane demo.
* <p>
* The "switchlist" List keeps track of all the objects added to the target
* frame for later manipulation. May be used in an update to store mixed
* switchboards with more than 1 connection and more than 1 bean type/range.
* <p>
* No DnD as panels will be automatically populated in order of the DCC address.
* New beans may be created from the Switchboard by right clicking an
* unconnected switch.
*
* @author Pete Cressman Copyright (c) 2009, 2010, 2011
* @author Egbert Broerse Copyright (c) 2017, 2018
*/
public class SwitchboardEditor extends Editor {
protected JMenuBar _menuBar;
private JMenu _editorMenu;
protected JMenu _editMenu;
protected JMenu _fileMenu;
protected JMenu _optionMenu;
private ArrayList<Positionable> _secondSelectionGroup;
private transient boolean panelChanged = false;
// Switchboard items
private JPanel navBarPanel = null;
ImageIcon iconPrev = new ImageIcon("resources/icons/misc/gui3/LafLeftArrow_m.gif");
private final JLabel prev = new JLabel(iconPrev);
ImageIcon iconNext = new ImageIcon("resources/icons/misc/gui3/LafRightArrow_m.gif");
private final JLabel next = new JLabel(iconNext);
private final int rangeBottom = 1;
private final int rangeTop = 100000; // for MERG etc where thousands = node number, total number on board limited to unconnectedRangeLimit anyway
private final int unconnectedRangeLimit = 400;
private final int rangeSizeWarning = 250;
private final int initialMax = 24;
private final JSpinner minSpinner = new JSpinner(new SpinnerNumberModel(rangeBottom, rangeBottom, rangeTop - 1, 1));
private final JSpinner maxSpinner = new JSpinner(new SpinnerNumberModel(initialMax, rangeBottom + 1, rangeTop, 1));
private final JCheckBox hideUnconnected = new JCheckBox(Bundle.getMessage("CheckBoxHideUnconnected"));
private final JCheckBox autoItemRange = new JCheckBox(Bundle.getMessage("CheckBoxAutoItemRange"));
private TargetPane switchboardLayeredPane; // JLayeredPane
static final String TURNOUT = Bundle.getMessage("Turnouts");
static final String SENSOR = Bundle.getMessage("Sensors");
static final String LIGHT = Bundle.getMessage("Lights");
private final String[] beanTypeStrings = {TURNOUT, SENSOR, LIGHT};
private JComboBox beanTypeList;
private char beanTypeChar;
JSpinner columns = new JSpinner(new SpinnerNumberModel(3, 1, 25, 1)); // columns is actually used for the number of rows
private final String[] switchShapeStrings = {
Bundle.getMessage("Buttons"),
Bundle.getMessage("Sliders"),
Bundle.getMessage("Keys"),
Bundle.getMessage("Symbols")
};
private JComboBox<String> switchShapeList;
private List<String> beanManuPrefixes = new ArrayList<>();
private JComboBox<String> beanManuNames;
private TitledBorder border;
private final String interact = Bundle.getMessage("SwitchboardInteractHint");
private final String noInteract = Bundle.getMessage("SwitchboardNoInteractHint");
// editor items (adapted from LayoutEditor toolbar)
private Color defaultTextColor = Color.BLACK;
private boolean _hideUnconnected = false;
private boolean _autoItemRange = true;
private final JTextArea help2 = new JTextArea(Bundle.getMessage("Help2"));
private final JTextArea help3 = new JTextArea(Bundle.getMessage("Help3", Bundle.getMessage("CheckBoxHideUnconnected")));
// saved state of options when panel was loaded or created
private transient boolean savedEditMode = true;
private transient boolean savedControlLayout = true; // menu option to turn this off
private final int height = 300;
private final int width = 300;
private final JCheckBoxMenuItem controllingBox = new JCheckBoxMenuItem(Bundle.getMessage("CheckBoxControlling"));
private final JCheckBoxMenuItem hideUnconnectedBox = new JCheckBoxMenuItem(Bundle.getMessage("CheckBoxHideUnconnected"));
private final JCheckBoxMenuItem autoItemRangeBox = new JCheckBoxMenuItem(Bundle.getMessage("CheckBoxAutoItemRange"));
private final JCheckBoxMenuItem showToolTipBox = new JCheckBoxMenuItem(Bundle.getMessage("CheckBoxShowTooltips"));
private final JRadioButtonMenuItem scrollBoth = new JRadioButtonMenuItem(Bundle.getMessage("ScrollBoth"));
private final JRadioButtonMenuItem scrollNone = new JRadioButtonMenuItem(Bundle.getMessage("ScrollNone"));
private final JRadioButtonMenuItem scrollHorizontal = new JRadioButtonMenuItem(Bundle.getMessage("ScrollHorizontal"));
private final JRadioButtonMenuItem scrollVertical = new JRadioButtonMenuItem(Bundle.getMessage("ScrollVertical"));
// Action commands
private static String LAYER_COMMAND = "layer";
private static String MANU_COMMAND = "manufacturer";
private static String SWITCHTYPE_COMMAND = "switchshape";
/**
* List of names/labels of all switches currently displayed. Refreshed
* during {@link #updatePressed()}
*/
private final List<String> switchlist = new ArrayList<>();
/**
* List with copies of BeanSwitch objects currently displayed to display on
* Web Server. Created by {@link #getSwitches()}
*/
protected ArrayList<BeanSwitch> _switches = new ArrayList<>();
/**
* Ctor
*/
public SwitchboardEditor() {
}
/**
* Ctor by a given name.
*
* @param name title to assign to the new SwitchBoard
*/
public SwitchboardEditor(String name) {
super(name, false, true);
init(name);
}
/**
* Initialize the newly created Switchboard.
*
* @param name the title of the switchboard content frame
*/
@SuppressWarnings("unchecked") // AbstractProxyManager of the right type is type-safe by definition
@Override
protected void init(String name) {
Container contentPane = getContentPane(); // the actual Editor configuration pane
setVisible(false); // start with Editor window hidden
setUseGlobalFlag(true); // always true for a Switchboard
// handle Editor close box clicked without deleting the Switchboard panel
super.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
super.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
log.debug("switchboardEditor close box selected");
setAllEditable(false);
setVisible(false); // hide Editor window
}
});
// make menus
_menuBar = new JMenuBar();
makeOptionMenu();
makeFileMenu();
setJMenuBar(_menuBar);
addHelpMenu("package.jmri.jmrit.display.SwitchboardEditor", true);
switchboardLayeredPane = new TargetPane(); // extends JLayeredPane();
switchboardLayeredPane.setPreferredSize(new Dimension(width, height));
border = BorderFactory.createTitledBorder(
BorderFactory.createLineBorder(defaultTextColor),
"temp",
TitledBorder.LEADING,
TitledBorder.ABOVE_BOTTOM,
getFont(),
defaultTextColor);
switchboardLayeredPane.setBorder(border);
// create contrast with background, should also specify border style
// specify title for turnout, sensor, light, mixed? (wait for the Editor to be created)
switchboardLayeredPane.addMouseMotionListener(this);
// add control pane and layered pane to this JPanel
JPanel beanSetupPane = new JPanel();
beanSetupPane.setLayout(new FlowLayout(FlowLayout.TRAILING));
JLabel beanTypeTitle = new JLabel(Bundle.getMessage("MakeLabel", Bundle.getMessage("BeanTypeLabel")));
beanSetupPane.add(beanTypeTitle);
beanTypeList = new JComboBox<>(beanTypeStrings);
beanTypeList.setSelectedIndex(0); // select bean type in comboBox
beanTypeList.setActionCommand(LAYER_COMMAND);
beanTypeList.addActionListener(this);
beanSetupPane.add(beanTypeList);
// add connection selection comboBox
beanTypeChar = getSwitchType().charAt(0); // translate from selectedIndex to char
log.debug("beanTypeChar set to [{}]", beanTypeChar);
JLabel beanManuTitle = new JLabel(Bundle.getMessage("MakeLabel", Bundle.getMessage("ConnectionLabel")));
beanSetupPane.add(beanManuTitle);
beanManuNames = new JComboBox<>();
if (getManager(beanTypeChar) instanceof jmri.managers.AbstractProxyManager) { // from abstractTableTabAction
jmri.managers.AbstractProxyManager proxy = (jmri.managers.AbstractProxyManager) getManager(beanTypeChar);
List<jmri.Manager<?>> managerList = proxy.getManagerList(); // picks up all managers to fetch
for (int x = 0; x < managerList.size(); x++) {
String manuPrefix = managerList.get(x).getSystemPrefix();
log.debug("Prefix{} = [{}]", x, manuPrefix);
String manuName = managerList.get(x).getMemo().getUserName();
log.debug("Connection name {} = [{}]", x, manuName);
beanManuNames.addItem(manuName); // add to comboBox
beanManuPrefixes.add(manuPrefix); // add to list
}
} else {
String manuPrefix = getManager(beanTypeChar).getSystemPrefix();
String manuName = getManager(beanTypeChar).getMemo().getUserName();
beanManuNames.addItem(manuName);
beanManuPrefixes.add(manuPrefix); // add to list (as only item)
}
beanManuNames.setSelectedIndex(0); // defaults to Internal on init()
beanManuNames.setActionCommand(MANU_COMMAND);
beanManuNames.addActionListener(this);
beanSetupPane.add(beanManuNames);
add(beanSetupPane);
// add shape combobox
JPanel switchShapePane = new JPanel();
switchShapePane.setLayout(new FlowLayout(FlowLayout.TRAILING));
JLabel switchShapeTitle = new JLabel(Bundle.getMessage("MakeLabel", Bundle.getMessage("SwitchShape")));
switchShapePane.add(switchShapeTitle);
switchShapeList = new JComboBox<>(switchShapeStrings);
switchShapeList.setSelectedIndex(0); // select Button choice in comboBox
switchShapeList.setActionCommand(SWITCHTYPE_COMMAND);
switchShapeList.addActionListener(this);
switchShapePane.add(switchShapeList);
// add column spinner
JLabel rowsLabel = new JLabel(Bundle.getMessage("NumberOfRows"));
switchShapePane.add(rowsLabel);
switchShapePane.add(columns);
add(switchShapePane);
JPanel checkboxPane = new JPanel();
checkboxPane.setLayout(new FlowLayout(FlowLayout.TRAILING));
// autoItemRange checkbox on panel
autoItemRange.setSelected(autoItemRange());
log.debug("autoItemRangeBox set to {}", autoItemRange.isSelected());
autoItemRange.addActionListener((ActionEvent event) -> {
setAutoItemRange(autoItemRange.isSelected());
autoItemRangeBox.setSelected(autoItemRange()); // also (un)check the box on the menu
// if set to checked, store the current range from the spinners
});
checkboxPane.add(autoItemRange);
autoItemRange.setToolTipText(Bundle.getMessage("AutoItemRangeTooltip"));
// hideUnconnected checkbox on panel
hideUnconnected.setSelected(hideUnconnected());
log.debug("hideUnconnectedBox set to {}", hideUnconnected.isSelected());
hideUnconnected.addActionListener((ActionEvent event) -> {
setHideUnconnected(hideUnconnected.isSelected());
hideUnconnectedBox.setSelected(hideUnconnected()); // also (un)check the box on the menu
help2.setVisible(!hideUnconnected() && (switchlist.size() != 0)); // and show/hide instruction line unless no items on board
});
checkboxPane.add(hideUnconnected);
add(checkboxPane);
switchboardLayeredPane.setLayout(new GridLayout(3, 8)); // initial layout params
// TODO do some calculation from JPanel size, icon size and determine optimal cols/rows
// Add at least 1 switch to pane to create switchList: done later, would be deleted soon
// provide a JLayeredPane to place the switches on
super.setTargetPanel(switchboardLayeredPane, makeFrame(name));
super.getTargetFrame().setSize(550, 330); // width x height
// TODO: Add component listener to handle frame resizing event
// set scrollbar initial state
setScroll(SCROLL_NONE);
scrollNone.setSelected(true);
super.setDefaultToolTip(new ToolTip(null, 0, 0, new Font("Serif", Font.PLAIN, 12),
Color.black, new Color(255, 250, 210), Color.black));
// register the resulting panel for later configuration
ConfigureManager cm = InstanceManager.getNullableDefault(jmri.ConfigureManager.class);
if (cm != null) {
cm.registerUser(this);
}
add(createControlPanel());
JPanel updatePanel = new JPanel();
JButton updateButton = new JButton(Bundle.getMessage("ButtonUpdate"));
updateButton.addActionListener((ActionEvent event) -> {
log.debug("Update clicked");
updatePressed();
setDirty();
});
updatePanel.add(updateButton);
contentPane.setLayout(new BoxLayout(contentPane, BoxLayout.PAGE_AXIS));
contentPane.add(updatePanel);
setupEditorPane(); // re-layout all the toolbar items
updatePressed(); // refresh default Switchboard, updates all buttons
pack();
}
/**
* Create a new set of switches after removing the current array.
* <p>
* Called by Update button click and automatically after loading a panel
* from XML (with all saved options set).
*/
public void updatePressed() {
log.debug("update _hideUnconnected = {}", _hideUnconnected);
if (_hideUnconnected && !hideUnconnected.isSelected()){
hideUnconnected.setSelected(true);
}
log.debug("update _autoItemRange = {}", _autoItemRange);
if (_autoItemRange && !autoItemRange.isSelected()){
autoItemRange.setSelected(true);
}
log.debug("update _editable = {}", _editable);
setVisible(_editable); // show/hide editor
log.debug("update _controlLayout = {}", allControlling());
// update selected address range
int range = (Integer) maxSpinner.getValue() - (Integer) minSpinner.getValue() + 1;
if (range > unconnectedRangeLimit && !hideUnconnected()) {
range = unconnectedRangeLimit;
maxSpinner.setValue((Integer) minSpinner.getValue() + range - 1); // fixed maximum number of items on a Switchboard to prevent memory overflow
}
// check for extreme number of items
log.debug("address range = {}", range);
if (range > rangeSizeWarning) {
// ask user if range is indeed desired
log.debug("Warning for big range");
int retval = JOptionPane.showOptionDialog(null,
Bundle.getMessage("LargeRangeWarning", range, Bundle.getMessage("CheckBoxHideUnconnected")),
Bundle.getMessage("WarningTitle"),
0, JOptionPane.INFORMATION_MESSAGE, null,
new Object[]{Bundle.getMessage("ButtonYes"), Bundle.getMessage("ButtonCancel")}, null);
log.debug("Retval: {}", retval);
if (retval != 0) {
return;
}
}
// if range is confirmed, go ahead with switchboard update
for (int i = switchlist.size() - 1; i >= 0; i--) {
// deleting items starting from 0 will result in skipping the even numbered items
switchboardLayeredPane.remove(i);
}
switchlist.clear(); // reset list
log.debug("switchlist cleared, size is now: {}", switchlist.size());
switchboardLayeredPane.setSize(width, height);
switchboardLayeredPane.setLayout(new GridLayout(Math.max((Integer) columns.getValue() % range, 1),
(Integer) columns.getValue())); // vertical, horizontal
log.debug("adding range for manu index {}", beanManuNames.getSelectedIndex());
addSwitchRange((Integer) minSpinner.getValue(),
(Integer) maxSpinner.getValue(),
beanTypeList.getSelectedIndex(),
beanManuPrefixes.get(beanManuNames.getSelectedIndex()),
switchShapeList.getSelectedIndex());
// update the title at the bottom of the switchboard to match (no) layout control
border.setTitle(beanManuNames.getSelectedItem().toString() + " "
+ beanTypeList.getSelectedItem().toString() + " - "
+ (allControlling() ? interact : noInteract));
help3.setVisible(switchlist.size() == 0); // show/hide help3 warning
help2.setVisible(switchlist.size() != 0); // hide help2 when help3 is shown vice versa (as no items are dimmed or not)
pack();
switchboardLayeredPane.repaint();
}
/**
* From default or user entry in Editor, fill the _targetpane with a series
* of Switches.
* <p>
* Items in range that can connect to existing beans in JMRI are active. The
* others are greyed out. Option to later connect (new) beans to switches.
*
* @param min starting ordinal of Switch address range
* @param max highest ordinal of Switch address range
* @param beanType index of selected item in Type comboBox, either T, S
* or L
* @param manuPrefix selected item in Connection comboBox, filled from
* active connections
* @param switchShape index of selected visual presentation of Switch shape
* selected in Type comboBox, choose either a JButton
* showing the name or (to do) a graphic image
*/
private void addSwitchRange(int min, int max, int beanType, String manuPrefix, int switchShape) {
log.debug("_hideUnconnected = {}", hideUnconnected());
String name;
BeanSwitch _switch;
NamedBean nb;
String _manu = manuPrefix; // cannot use All group as in Tables
log.debug("_manu = {}", _manu);
String _insert = "";
if (_manu.startsWith("M")) {
_insert = "+"; // for CANbus.MERG On event
}
for (int i = min; i <= max; i++) {
switch (beanType) {
case 0:
name = _manu + "T" + _insert + i;
nb = jmri.InstanceManager.turnoutManagerInstance().getTurnout(name);
break;
case 1:
name = _manu + "S" + _insert + i;
nb = jmri.InstanceManager.sensorManagerInstance().getSensor(name);
break;
case 2:
name = _manu + "L" + _insert + i;
nb = jmri.InstanceManager.lightManagerInstance().getLight(name);
break;
default:
log.error("addSwitchRange: cannot parse bean name. manuPrefix = {}; i = {}", manuPrefix, i);
return;
}
if (nb == null && hideUnconnected()) {
continue; // skip i
}
_switch = new BeanSwitch(i, nb, name, switchShape, this); // add button instance i
if (nb == null) {
_switch.setEnabled(false); // not connected
} else {
// set switch to display current bean state
_switch.displayState(nb.getState());
}
switchboardLayeredPane.add(_switch);
switchlist.add(name); // add to total number of switches on JLayeredPane
log.debug("Added switch {}", name);
// keep total number of switches below practical total of 400 (20 x 20 items)
if (switchlist.size() >= unconnectedRangeLimit) {
log.warn("switchboards are limited to {} items", unconnectedRangeLimit);
break;
}
}
}
/**
* Create the setup pane for the top of the frame. From layeredpane demo
*/
private JPanel createControlPanel() {
JPanel controls = new JPanel();
// navigation top row and range to set
navBarPanel = new JPanel();
navBarPanel.setLayout(new BoxLayout(navBarPanel, BoxLayout.X_AXIS));
navBarPanel.add(prev);
prev.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int oldMin = getMinSpinner();
int oldMax = getMaxSpinner();
int range = Math.max(oldMax - oldMin + 1, 1); // make sure range > 0
log.debug("prev range was {}, oldMin ={}, oldMax ={}", range, oldMin, oldMax);
setMinSpinner(Math.max((oldMin - range), rangeBottom)); // first set new min
if (_autoItemRange) {
setMaxSpinner(Math.max((oldMax - range), range)); // set new max (only if auto)
}
log.debug("new prev range = {}, newMin ={}, newMax ={}", range, getMinSpinner(), getMaxSpinner());
}
});
prev.setToolTipText(Bundle.getMessage("PreviousToolTip", Bundle.getMessage("CheckBoxAutoItemRange")));
navBarPanel.add(new JLabel(Bundle.getMessage("MakeLabel", Bundle.getMessage("From"))));
JComponent minEditor = minSpinner.getEditor();
// enlarge minSpinner editor text field width
JFormattedTextField minTf = ((JSpinner.DefaultEditor) minEditor).getTextField();
minTf.setColumns(5);
minSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
JSpinner spinner = (JSpinner) e.getSource();
int value = (int)spinner.getValue();
// stop if value >= maxSpinner -1 (range <= 0)
if (value >= (Integer) maxSpinner.getValue() - 1) {
maxSpinner.setValue(value + 1);
}
}
});
navBarPanel.add(minSpinner);
navBarPanel.add(new JLabel(Bundle.getMessage("MakeLabel", Bundle.getMessage("UpTo"))));
// enlarge maxSpinner editor text field width
JComponent maxEditor = maxSpinner.getEditor();
JFormattedTextField maxTf = ((JSpinner.DefaultEditor) maxEditor).getTextField();
maxTf.setColumns(5);
maxSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
JSpinner spinner = (JSpinner) e.getSource();
int value = (int)spinner.getValue();
// stop if value <= minSpinner + 1 (range <= 0)
if (value <= (Integer) minSpinner.getValue() + 1) {
minSpinner.setValue(value - 1);
}
}
});
navBarPanel.add(maxSpinner);
navBarPanel.add(next);
next.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int oldMin = getMinSpinner();
int oldMax = getMaxSpinner();
int range = Math.max(oldMax - oldMin + 1, 1); // make sure range > 0
log.debug("nxt range was {}, oldMin ={}, oldMax ={}", range, oldMin, oldMax);
setMaxSpinner(Math.min((oldMax + range), rangeTop)); // first set new max
if (_autoItemRange) {
setMinSpinner(Math.min(oldMin + range, rangeTop - range + 1)); // set new min (only if auto)
}
log.debug("new nxt range = {}, newMin ={}, newMax ={}", range, getMinSpinner(), getMaxSpinner());
}
});
next.setToolTipText(Bundle.getMessage("NextToolTip", Bundle.getMessage("CheckBoxAutoItemRange")));
navBarPanel.add(Box.createHorizontalGlue());
controls.add(navBarPanel); // put items on 2nd Editor Panel
controls.setBorder(BorderFactory.createTitledBorder(Bundle.getMessage("SelectRangeTitle")));
return controls;
}
private int getMinSpinner() {
return (Integer) minSpinner.getValue();
}
private int getMaxSpinner() {
return (Integer) maxSpinner.getValue();
}
private void setMinSpinner(int value) {
minSpinner.setValue(value);
}
private void setMaxSpinner(int value) {
maxSpinner.setValue(value);
}
private void setupEditorPane() {
// Initial setup
Container contentPane = getContentPane(); // Editor (configuration) pane
JPanel innerBorderPanel = new JPanel();
innerBorderPanel.setLayout(new BoxLayout(innerBorderPanel, BoxLayout.PAGE_AXIS));
TitledBorder TitleBorder = BorderFactory.createTitledBorder(Bundle.getMessage("SwitchboardHelpTitle"));
innerBorderPanel.setBorder(TitleBorder);
innerBorderPanel.add(new JTextArea(Bundle.getMessage("Help1")));
// help2 explains: dimmed icons = unconnected
innerBorderPanel.add(help2);
if (!hideUnconnected()) {
help2.setVisible(false); // hide this text when hideUnconnected() is set to true from menu or checkbox
}
// help3 warns: no icons to show on switchboard
help3.setForeground(Color.red);
innerBorderPanel.add(help3);
help3.setVisible(false); // initially hide help3 warning text
contentPane.add(innerBorderPanel);
}
//@Override
protected void makeOptionMenu() {
_optionMenu = new JMenu(Bundle.getMessage("MenuOptions"));
_menuBar.add(_optionMenu, 0);
// controllable item
_optionMenu.add(controllingBox);
controllingBox.addActionListener((ActionEvent event) -> {
setAllControlling(controllingBox.isSelected());
// update the title on the switchboard to match (no) layout control
border.setTitle(beanManuNames.getSelectedItem().toString() + " "
+ beanTypeList.getSelectedItem().toString() + " - "
+ (allControlling() ? interact : noInteract));
switchboardLayeredPane.repaint();
log.debug("border title updated");
});
controllingBox.setSelected(allControlling());
// hideUnconnected item
_optionMenu.add(hideUnconnectedBox);
hideUnconnectedBox.addActionListener((ActionEvent event) -> {
setHideUnconnected(hideUnconnectedBox.isSelected());
hideUnconnected.setSelected(hideUnconnected()); // also (un)check the box on the editor
help2.setVisible(!hideUnconnected() && (switchlist.size() != 0)); // and show/hide instruction line unless no items on board
});
hideUnconnectedBox.setSelected(hideUnconnected());
// autoItemRange item
_optionMenu.add(autoItemRangeBox);
autoItemRangeBox.addActionListener((ActionEvent event) -> {
setAutoItemRange(autoItemRangeBox.isSelected());
autoItemRange.setSelected(autoItemRange()); // also (un)check the box on the editor
});
autoItemRangeBox.setSelected(autoItemRange());
// show tooltip item
_optionMenu.add(showToolTipBox);
showToolTipBox.addActionListener((ActionEvent e) -> {
setAllShowToolTip(showToolTipBox.isSelected());
});
showToolTipBox.setSelected(showToolTip());
// Show/Hide Scroll Bars
JMenu scrollMenu = new JMenu(Bundle.getMessage("ComboBoxScrollable"));
_optionMenu.add(scrollMenu);
ButtonGroup scrollGroup = new ButtonGroup();
scrollGroup.add(scrollBoth);
scrollMenu.add(scrollBoth);
scrollBoth.addActionListener((ActionEvent event) -> {
setScroll(SCROLL_BOTH);
});
scrollGroup.add(scrollNone);
scrollMenu.add(scrollNone);
scrollNone.addActionListener((ActionEvent event) -> {
setScroll(SCROLL_NONE);
});
scrollGroup.add(scrollHorizontal);
scrollMenu.add(scrollHorizontal);
scrollHorizontal.addActionListener((ActionEvent event) -> {
setScroll(SCROLL_HORIZONTAL);
});
scrollGroup.add(scrollVertical);
scrollMenu.add(scrollVertical);
scrollVertical.addActionListener((ActionEvent event) -> {
setScroll(SCROLL_VERTICAL);
});
// add background color menu item
JMenuItem backgroundColorMenuItem = new JMenuItem(Bundle.getMessage("SetBackgroundColor", "..."));
_optionMenu.add(backgroundColorMenuItem);
backgroundColorMenuItem.addActionListener((ActionEvent event) -> {
Color desiredColor = JmriColorChooser.showDialog(this,
Bundle.getMessage("SetBackgroundColor", ""),
defaultBackgroundColor);
if (desiredColor!=null && !defaultBackgroundColor.equals(desiredColor)) {
// if new bgColor matches the defaultTextColor, ask user as labels will become unreadable
if (desiredColor.equals(defaultTextColor)) {
int retval = JOptionPane.showOptionDialog(null,
Bundle.getMessage("ColorIdenticalWarning"), Bundle.getMessage("WarningTitle"),
0, JOptionPane.INFORMATION_MESSAGE, null,
new Object[]{Bundle.getMessage("ButtonOK"), Bundle.getMessage("ButtonCancel")}, null);
log.debug("Retval: {}", retval);
if (retval != 0) {
return;
}
}
defaultBackgroundColor = desiredColor;
setBackgroundColor(desiredColor);
setDirty(true);
switchboardLayeredPane.repaint();
}
});
// add text color menu item
JMenuItem textColorMenuItem = new JMenuItem(Bundle.getMessage("DefaultTextColor", "..."));
_optionMenu.add(textColorMenuItem);
textColorMenuItem.addActionListener((ActionEvent event) -> {
Color desiredColor = JmriColorChooser.showDialog(this,
Bundle.getMessage("DefaultTextColor", ""),
defaultTextColor);
if (desiredColor!=null && !defaultTextColor.equals(desiredColor)) {
// if new defaultTextColor matches bgColor, ask user as labels will become unreadable
if (desiredColor.equals(defaultBackgroundColor)) {
int retval = JOptionPane.showOptionDialog(null,
Bundle.getMessage("ColorIdenticalWarning"), Bundle.getMessage("WarningTitle"),
0, JOptionPane.INFORMATION_MESSAGE, null,
new Object[]{Bundle.getMessage("ButtonOK"), Bundle.getMessage("ButtonCancel")}, null);
log.debug("Retval: {}", retval);
if (retval != 0) {
return;
}
}
defaultTextColor = desiredColor;
setDirty(true);
switchboardLayeredPane.repaint();
JmriColorChooser.addRecentColor(desiredColor);
}
});
}
private void makeFileMenu() {
_fileMenu = new JMenu(Bundle.getMessage("MenuFile"));
_menuBar.add(_fileMenu, 0);
_fileMenu.add(new jmri.jmrit.display.NewPanelAction(Bundle.getMessage("MenuItemNew")));
_fileMenu.add(new jmri.configurexml.StoreXmlUserAction(Bundle.getMessage("MenuItemStore")));
JMenuItem editItem = new JMenuItem(Bundle.getMessage("renamePanelMenu", "..."));
PositionableJComponent z = new PositionableJComponent(this);
z.setScale(getPaintScale());
editItem.addActionListener(CoordinateEdit.getNameEditAction(z));
_fileMenu.add(editItem);
_fileMenu.addSeparator();
JMenuItem deleteItem = new JMenuItem(Bundle.getMessage("DeletePanel"));
_fileMenu.add(deleteItem);
deleteItem.addActionListener((ActionEvent event) -> {
if (deletePanel()) {
dispose();
}
});
_fileMenu.addSeparator();
editItem = new JMenuItem(Bundle.getMessage("CloseEditor"));
_fileMenu.add(editItem);
editItem.addActionListener((ActionEvent event) -> {
log.debug("switchboardeditor edit menu CloseEditor selected");
setAllEditable(false);
setVisible(false); // hide Editor pane
});
}
public void setDefaultTextColor(Color color) {
defaultTextColor = color;
}
/**
* @param color the string containing a color settable using {@link jmri.util.ColorUtil#stringToColor(String)}
* @deprecated since 4.15.7; use {@link #setDefaultTextColor(Color)} instead
*/
@Deprecated
public void setDefaultTextColor(String color) {
setDefaultTextColor(ColorUtil.stringToColor(color));
}
public String getDefaultTextColor() {
return ColorUtil.colorToColorName(defaultTextColor);
}
public Color getDefaultTextColorAsColor() {
return defaultTextColor;
}
/**
* Load from xml and set bg color of _targetpanel as well as variable.
*
* @param color RGB Color for switchboard background and beanSwitches
*/
public void setDefaultBackgroundColor(Color color) {
setBackgroundColor(color); // via Editor
defaultBackgroundColor = color;
}
/**
* Get current default background color.
*
* @return background color of this Switchboard
*/
public Color getDefaultBackgroundColor() {
return defaultBackgroundColor;
}
// *********************** end Menus ************************
@Override
public void setAllEditable(boolean edit) {
log.debug("_editable set to {}", edit);
if (edit) {
if (_editorMenu != null) {
_menuBar.remove(_editorMenu);
}
if (_optionMenu == null) {
makeOptionMenu();
} else {
_menuBar.add(_optionMenu, 0);
}
if (_fileMenu == null) {
makeFileMenu();
} else {
_menuBar.add(_fileMenu, 0);
}
log.debug("added File and Options menubar");
//contentPane.SetUpdateButtonEnabled(false);
} else {
if (_fileMenu != null) {
_menuBar.remove(_fileMenu);
}
if (_optionMenu != null) {
_menuBar.remove(_optionMenu);
}
if (_editorMenu == null) {
_editorMenu = new JMenu(Bundle.getMessage("MenuEdit"));
_editorMenu.add(new AbstractAction(Bundle.getMessage("OpenEditor")) {
@Override
public void actionPerformed(ActionEvent e) {
setAllEditable(true);
log.debug("Switchboard Editor Open Editor menu called");
}
});
_menuBar.add(_editorMenu, 0);
}
//contentPane.SetUpdateButtonEnabled(true);
}
super.setAllEditable(edit);
super.setTitle();
_menuBar.revalidate();
}
@Override
public void setUseGlobalFlag(boolean set) {
controllingBox.setEnabled(set);
super.setUseGlobalFlag(set);
}
@Override
public void setTitle() {
String name = getName(); // get name of JFrame
log.debug("JFrame name = {}", name);
if (name == null || name.length() == 0) {
name = Bundle.getMessage("SwitchboardDefaultName", "");
}
super.setTitle(name + " " + Bundle.getMessage("LabelEditor"));
super.getTargetFrame().setTitle(name);
}
/**
* Control whether target panel items without a connection to the layout are
* displayed.
*
* @param state true to hide all in range
*/
public void setHideUnconnected(boolean state) {
_hideUnconnected = state;
}
public boolean hideUnconnected() {
return _hideUnconnected;
}
/**
* Control whether range of items is automatically limited.
*
* @param state true to calculate upper limit from lowest value set (default)
*/
public void setAutoItemRange(boolean state) {
_autoItemRange = state;
}
public boolean autoItemRange() {
return _autoItemRange;
}
/**
* Allow external reset of dirty bit.
*/
public void resetDirty() {
setDirty(false);
savedEditMode = isEditable();
savedControlLayout = allControlling();
}
/**
* Allow external set of dirty bit.
*/
public void setDirty(boolean val) {
panelChanged = val;
}
public void setDirty() {
setDirty(true);
}
/**
* Check the dirty state.
*/
public boolean isDirty() {
return panelChanged;
}
// ********************** load/store board *******************
/**
* Load Range minimum.
*
* @param rangemin lowest address to show
*/
public void setPanelMenuRangeMin(int rangemin) {
minSpinner.setValue(rangemin);
}
/**
* Load Range maximum.
*
* @param rangemax highest address to show
*/
public void setPanelMenuRangeMax(int rangemax) {
maxSpinner.setValue(rangemax);
}
/**
* Store Range minimum.
*
* @return lowest address to show
*/
public int getPanelMenuRangeMin() {
return (int) minSpinner.getValue();
}
/**
* Store Range maximum.
*
* @return highest address to show
*/
public int getPanelMenuRangeMax() {
return (int) maxSpinner.getValue();
}
private String typePrefix;
private String type;
// ***************** Store & Load xml ********************
/**
* Store bean type.
*
* @return bean type prefix
*/
public String getSwitchType() {
String switchType = beanTypeList.getSelectedItem().toString();
if (switchType.equals(LIGHT)) { // switch-case doesn't work here
typePrefix = "L";
} else if (switchType.equals(SENSOR)) {
typePrefix = "S";
} else { // Turnout
typePrefix = "T";
}
return typePrefix;
}
/**
* Get bean type name.
*
* @return bean type name
*/
public String getSwitchTypeName() {
return type;
}
/**
* Load bean type.
*
* @param prefix the bean type prefix
*/
public void setSwitchType(String prefix) {
typePrefix = prefix;
switch (typePrefix) {
case "L":
type = LIGHT;
break;
case "S":
type = SENSOR;
break;
default: // Turnouts
type = TURNOUT;
}
try {
beanTypeList.setSelectedItem(type);
} catch (IllegalArgumentException e) {
log.error("invalid bean type [{}] in Switchboard", typePrefix);
}
}
/**
* Store connection type.
*
* @return bean connection prefix
*/
public String getSwitchManu() {
return this.beanManuPrefixes.get(beanManuNames.getSelectedIndex());
}