/
GenericDialog.java
1588 lines (1476 loc) · 50.8 KB
/
GenericDialog.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 ij.gui;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import ij.*;
import ij.plugin.frame.Recorder;
import ij.plugin.ScreenGrabber;
import ij.plugin.filter.PlugInFilter;
import ij.plugin.filter.PlugInFilterRunner;
import ij.util.Tools;
import ij.macro.*;
/**
* This class is a customizable modal dialog box. Here is an example
* GenericDialog with one string field and two numeric fields:
* <pre>
* public class Generic_Dialog_Example implements PlugIn {
* static String title="Example";
* static int width=512,height=512;
* public void run(String arg) {
* GenericDialog gd = new GenericDialog("New Image");
* gd.addStringField("Title: ", title);
* gd.addNumericField("Width: ", width, 0);
* gd.addNumericField("Height: ", height, 0);
* gd.showDialog();
* if (gd.wasCanceled()) return;
* title = gd.getNextString();
* width = (int)gd.getNextNumber();
* height = (int)gd.getNextNumber();
* IJ.newImage(title, "8-bit", width, height, 1);
* }
* }
* </pre>
* To work with macros, the first word of each component label must be
* unique. If this is not the case, add underscores, which will be converted
* to spaces when the dialog is displayed. For example, change the checkbox labels
* "Show Quality" and "Show Residue" to "Show_Quality" and "Show_Residue".
*/
public class GenericDialog extends Dialog implements ActionListener, TextListener,
FocusListener, ItemListener, KeyListener, AdjustmentListener, WindowListener {
protected Vector numberField, stringField, checkbox, choice, slider, radioButtonGroups;
protected TextArea textArea1, textArea2;
protected Vector defaultValues,defaultText,defaultStrings,defaultChoiceIndexes;
protected Component theLabel;
private Button cancel, okay, no, help;
private String okLabel = " OK ";
private String cancelLabel = "Cancel";
private String helpLabel = "Help";
private boolean wasCanceled, wasOKed;
private int nfIndex, sfIndex, cbIndex, choiceIndex, textAreaIndex, radioButtonIndex;
private GridBagConstraints c;
private boolean firstNumericField=true;
private boolean firstSlider=true;
private boolean invalidNumber;
private String errorMessage;
private Hashtable labels;
private boolean macro;
private String macroOptions;
private boolean addToSameRow;
private boolean addToSameRowCalled;
private int topInset, leftInset, bottomInset;
private boolean customInsets;
private Vector sliderIndexes, sliderScales, sliderDigits;
private Checkbox previewCheckbox; // the "Preview" Checkbox, if any
private Vector dialogListeners; // the Objects to notify on user input
private PlugInFilterRunner pfr; // the PlugInFilterRunner for automatic preview
private String previewLabel = " Preview";
private final static String previewRunning = "wait...";
private boolean recorderOn; // whether recording is allowed
private boolean yesNoCancel;
private char echoChar;
private boolean hideCancelButton;
private boolean centerDialog = true;
private String helpURL;
private String yesLabel, noLabel;
private boolean smartRecording;
private Vector imagePanels;
private static GenericDialog instance;
private boolean firstPaint = true;
private boolean fontSizeSet;
/** Creates a new GenericDialog with the specified title. Uses the current image
image window as the parent frame or the ImageJ frame if no image windows
are open. Dialog parameters are recorded by ImageJ's command recorder but
this requires that the first word of each label be unique. */
public GenericDialog(String title) {
this(title, getParentFrame());
}
private static Frame getParentFrame() {
Frame parent = WindowManager.getCurrentImage()!=null?
(Frame)WindowManager.getCurrentImage().getWindow():IJ.getInstance()!=null?IJ.getInstance():new Frame();
if (IJ.isMacOSX() && IJ.isJava18()) {
ImageJ ij = IJ.getInstance();
if (ij!=null && ij.isActive())
parent = ij;
else
parent = null;
}
return parent;
}
/** Creates a new GenericDialog using the specified title and parent frame. */
public GenericDialog(String title, Frame parent) {
super(parent==null?new Frame():parent, title, true);
if (Prefs.blackCanvas) {
setForeground(SystemColor.controlText);
setBackground(SystemColor.control);
}
GridBagLayout grid = new GridBagLayout();
c = new GridBagConstraints();
setLayout(grid);
macroOptions = Macro.getOptions();
//IJ.log("macroOptions: "+macroOptions+" "+title);
macro = macroOptions!=null;
addKeyListener(this);
addWindowListener(this);
}
/** Adds a numeric field. The first word of the label must be
unique or command recording will not work.
* @param label the label
* @param defaultValue value to be initially displayed
* @param digits number of digits to right of decimal point
*/
public void addNumericField(String label, double defaultValue, int digits) {
addNumericField(label, defaultValue, digits, 6, null);
}
/** Adds a numeric field. The first word of the label must be
unique or command recording will not work.
* @param label the label
* @param defaultValue value to be initially displayed
* @param digits number of digits to right of decimal point
* @param columns width of field in characters
* @param units a string displayed to the right of the field
*/
public void addNumericField(String label, double defaultValue, int digits, int columns, String units) {
String label2 = label;
if (label2.indexOf('_')!=-1)
label2 = label2.replace('_', ' ');
Label theLabel = makeLabel(label2);
if (addToSameRow) {
c.gridx = GridBagConstraints.RELATIVE;
c.insets.left = 10;
} else {
c.gridx = 0; c.gridy++;
if (firstNumericField)
c.insets = getInsets(5, 0, 3, 0); // top, left, bottom, right
else
c.insets = getInsets(0, 0, 3, 0);
}
c.anchor = GridBagConstraints.EAST;
c.gridwidth = 1;
//IJ.log("x="+c.gridx+", y= "+c.gridy+", width="+c.gridwidth+", ancher= "+c.anchor+" "+c.insets);
add(theLabel, c);
if (addToSameRow) {
c.insets.left = 0;
addToSameRow = false;
}
if (numberField==null) {
numberField = new Vector(5);
defaultValues = new Vector(5);
defaultText = new Vector(5);
}
if (IJ.isWindows()) columns -= 2;
if (columns<1) columns = 1;
String defaultString = IJ.d2s(defaultValue, digits);
if (Double.isNaN(defaultValue))
defaultString = "";
TextField tf = new TextField(defaultString, columns);
if (IJ.isLinux()) tf.setBackground(Color.white);
tf.addActionListener(this);
tf.addTextListener(this);
tf.addFocusListener(this);
tf.addKeyListener(this);
numberField.addElement(tf);
defaultValues.addElement(new Double(defaultValue));
defaultText.addElement(tf.getText());
c.gridx = GridBagConstraints.RELATIVE;
c.anchor = GridBagConstraints.WEST;
tf.setEditable(true);
//if (firstNumericField) tf.selectAll();
firstNumericField = false;
if (units==null||units.equals("")) {
add(tf, c);
} else {
Panel panel = new Panel();
panel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.add(tf);
panel.add(new Label(" "+units));
add(panel, c);
}
if (Recorder.record || macro)
saveLabel(tf, label);
}
private Label makeLabel(String label) {
if (IJ.isMacintosh())
label += " ";
return new Label(label);
}
/** Saves the label for given component, for macro recording and for accessing the component in macros. */
private void saveLabel(Object component, String label) {
if (labels==null)
labels = new Hashtable();
if (label.length()>0)
label = Macro.trimKey(label.trim());
if (hasLabel(label)) { // not a unique label?
label += "_0";
for (int n=1; hasLabel(label); n++) { // while still not a unique label
label = label.substring(0, label.lastIndexOf('_')); //remove counter
label += "_"+n;
}
}
labels.put(component, label);
}
/** Returns whether the list of labels for macro recording or macro creation contains a given label. */
private boolean hasLabel(String label) {
for (Object o : labels.keySet())
if (labels.get(o).equals(label)) return true;
return false;
}
/** Adds an 8 column text field.
* @param label the label
* @param defaultText the text initially displayed
*/
public void addStringField(String label, String defaultText) {
addStringField(label, defaultText, 8);
}
/** Adds a text field.
* @param label the label
* @param defaultText text initially displayed
* @param columns width of the text field. If columns is 8 or more, additional items may be added to this line with addToSameRow()
*/
public void addStringField(String label, String defaultText, int columns) {
String label2 = label;
if (label2.indexOf('_')!=-1)
label2 = label2.replace('_', ' ');
Label theLabel = makeLabel(label2);
boolean custom = customInsets;
if (addToSameRow) {
c.gridx = GridBagConstraints.RELATIVE;
addToSameRow = false;
} else {
c.gridx = 0; c.gridy++;
if (stringField==null)
c.insets = getInsets(5, 0, 5, 0); // top, left, bottom, right
else
c.insets = getInsets(0, 0, 5, 0);
}
c.anchor = GridBagConstraints.EAST;
c.gridwidth = 1;
add(theLabel, c);
if (stringField==null) {
stringField = new Vector(4);
defaultStrings = new Vector(4);
}
TextField tf = new TextField(defaultText, columns);
if (IJ.isLinux()) tf.setBackground(Color.white);
tf.setEchoChar(echoChar);
echoChar = 0;
tf.addActionListener(this);
tf.addTextListener(this);
tf.addFocusListener(this);
tf.addKeyListener(this);
c.gridx = GridBagConstraints.RELATIVE;
c.anchor = GridBagConstraints.WEST;
c.gridwidth = columns <= 8 ? 1 : GridBagConstraints.REMAINDER;
c.insets.left = 0;
tf.setEditable(true);
add(tf, c);
stringField.addElement(tf);
defaultStrings.addElement(defaultText);
if (Recorder.record || macro)
saveLabel(tf, label);
}
/** Sets the echo character for the next string field. */
public void setEchoChar(char echoChar) {
this.echoChar = echoChar;
}
/** Adds a checkbox.
* @param label the label
* @param defaultValue the initial state
*/
public void addCheckbox(String label, boolean defaultValue) {
addCheckbox(label, defaultValue, false);
}
/** Adds a checkbox; does not make it recordable if isPreview is true.
* With isPreview true, the checkbox can be referred to as previewCheckbox
* from hereon.
*/
private void addCheckbox(String label, boolean defaultValue, boolean isPreview) {
String label2 = label;
if (label2.indexOf('_')!=-1)
label2 = label2.replace('_', ' ');
if (addToSameRow) {
c.gridx = GridBagConstraints.RELATIVE;
c.insets.left = 10;
addToSameRow = false;
} else {
c.gridx = 0; c.gridy++;
if (checkbox==null)
c.insets = getInsets(15, 20, 0, 0); // top, left, bottom, right
else
c.insets = getInsets(0, 20, 0, 0);
}
c.anchor = GridBagConstraints.WEST;
c.gridwidth = 2;
if (checkbox==null)
checkbox = new Vector(4);
Checkbox cb = new Checkbox(label2);
cb.setState(defaultValue);
cb.addItemListener(this);
cb.addKeyListener(this);
add(cb, c);
c.insets.left = 0;
checkbox.addElement(cb);
if (!isPreview &&(Recorder.record || macro)) //preview checkbox is not recordable
saveLabel(cb, label);
if (isPreview) previewCheckbox = cb;
}
/** Adds a checkbox labelled "Preview" for "automatic" preview.
* The reference to this checkbox can be retrieved by getPreviewCheckbox()
* and it provides the additional method previewRunning for optical
* feedback while preview is prepared.
* PlugInFilters can have their "run" method automatically called for
* preview under the following conditions:
* - the PlugInFilter must pass a reference to itself (i.e., "this") as an
* argument to the AddPreviewCheckbox
* - it must implement the DialogListener interface and set the filter
* parameters in the dialogItemChanged method.
* - it must have DIALOG and PREVIEW set in its flags.
* A previewCheckbox is always off when the filter is started and does not get
* recorded by the Macro Recorder.
*
* @param pfr A reference to the PlugInFilterRunner calling the PlugInFilter
* if automatic preview is desired, null otherwise.
*/
public void addPreviewCheckbox(PlugInFilterRunner pfr) {
if (previewCheckbox != null)
return;
ImagePlus imp = WindowManager.getCurrentImage();
if (imp!=null && imp.isComposite() && ((CompositeImage)imp).getMode()==IJ.COMPOSITE)
return;
this.pfr = pfr;
addCheckbox(previewLabel, false, true);
}
/** Add the preview checkbox with user-defined label; for details see the
* addPreviewCheckbox method with standard "Preview" label.
* Adds the checkbox when the current image is a CompositeImage
* in "Composite" mode, unlike the one argument version.
* Note that a GenericDialog can have only one PreviewCheckbox.
*/
public void addPreviewCheckbox(PlugInFilterRunner pfr, String label) {
if (previewCheckbox!=null)
return;
previewLabel = label;
this.pfr = pfr;
addCheckbox(previewLabel, false, true);
}
/** Adds a group of checkboxs using a grid layout.
* @param rows the number of rows
* @param columns the number of columns
* @param labels the labels
* @param defaultValues the initial states
*/
public void addCheckboxGroup(int rows, int columns, String[] labels, boolean[] defaultValues) {
addCheckboxGroup(rows, columns, labels, defaultValues, null);
}
/** Adds a group of checkboxs using a grid layout.
* @param rows the number of rows
* @param columns the number of columns
* @param labels the labels
* @param defaultValues the initial states
* @param headings the column headings
* Example: http://imagej.nih.gov/ij/plugins/multi-column-dialog/index.html
*/
public void addCheckboxGroup(int rows, int columns, String[] labels, boolean[] defaultValues, String[] headings) {
Panel panel = new Panel();
int nRows = headings!=null?rows+1:rows;
panel.setLayout(new GridLayout(nRows, columns, 6, 0));
int startCBIndex = cbIndex;
if (checkbox==null)
checkbox = new Vector(12);
if (headings!=null) {
Font font = new Font("SansSerif", Font.BOLD, 12);
for (int i=0; i<columns; i++) {
if (i>headings.length-1 || headings[i]==null)
panel.add(new Label(""));
else {
Label label = new Label(headings[i]);
label.setFont(font);
panel.add(label);
}
}
}
int i1 = 0;
int[] index = new int[labels.length];
for (int row=0; row<rows; row++) {
for (int col=0; col<columns; col++) {
int i2 = col*rows+row;
if (i2>=labels.length) break;
index[i1] = i2;
String label = labels[i1];
if (label==null || label.length()==0) {
Label lbl = new Label("");
panel.add(lbl);
i1++;
continue;
}
if (label.indexOf('_')!=-1)
label = label.replace('_', ' ');
Checkbox cb = new Checkbox(label);
checkbox.addElement(cb);
cb.setState(defaultValues[i1]);
cb.addItemListener(this);
if (Recorder.record || macro)
saveLabel(cb, labels[i1]);
if (IJ.isLinux()) {
Panel panel2 = new Panel();
panel2.setLayout(new BorderLayout());
panel2.add("West", cb);
panel.add(panel2);
} else
panel.add(cb);
i1++;
}
}
c.gridx = 0; c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.WEST;
c.insets = getInsets(10, 0, 0, 0);
addToSameRow = false;
add(panel, c);
}
/** Adds a radio button group.
* @param label group label (or null)
* @param items radio button labels
* @param rows number of rows
* @param columns number of columns
* @param defaultItem button initially selected
*/
public void addRadioButtonGroup(String label, String[] items, int rows, int columns, String defaultItem) {
addToSameRow = false;
Panel panel = new Panel();
int n = items.length;
panel.setLayout(new GridLayout(rows, columns, 0, 0));
CheckboxGroup cg = new CheckboxGroup();
for (int i=0; i<n; i++) {
Checkbox cb = new Checkbox(items[i],cg,items[i].equals(defaultItem));
cb.addItemListener(this);
panel.add(cb);
}
if (radioButtonGroups==null)
radioButtonGroups = new Vector();
radioButtonGroups.addElement(cg);
Insets insets = getInsets(5, 10, 0, 0);
if (label==null || label.equals("")) {
label = "rbg"+radioButtonGroups.size();
insets.top += 5;
} else {
setInsets(10, insets.left, 0);
addMessage(label);
insets.top = 2;
insets.left += 10;
}
c.gridx = 0; c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.WEST;
c.insets = new Insets(insets.top, insets.left, 0, 0);
add(panel, c);
if (Recorder.record || macro)
saveLabel(cg, label);
}
/** Adds a popup menu.
* @param label the label
* @param items the menu items
* @param defaultItem the menu item initially selected
*/
public void addChoice(String label, String[] items, String defaultItem) {
String label2 = label;
if (label2.indexOf('_')!=-1)
label2 = label2.replace('_', ' ');
Label theLabel = makeLabel(label2);
if (addToSameRow) {
c.gridx = GridBagConstraints.RELATIVE;
addToSameRow = false;
} else {
c.gridx = 0; c.gridy++;
if (choice==null)
c.insets = getInsets(5, 0, 5, 0);
else
c.insets = getInsets(0, 0, 5, 0);
}
c.anchor = GridBagConstraints.EAST;
c.gridwidth = 1;
if (choice==null) {
choice = new Vector(4);
defaultChoiceIndexes = new Vector(4);
}
add(theLabel, c);
Choice thisChoice = new Choice();
thisChoice.addKeyListener(this);
thisChoice.addItemListener(this);
for (int i=0; i<items.length; i++)
thisChoice.addItem(items[i]);
if (defaultItem!=null)
thisChoice.select(defaultItem);
else
thisChoice.select(0);
c.gridx = GridBagConstraints.RELATIVE;
c.anchor = GridBagConstraints.WEST;
add(thisChoice, c);
choice.addElement(thisChoice);
int index = thisChoice.getSelectedIndex();
defaultChoiceIndexes.addElement(new Integer(index));
if (Recorder.record || macro)
saveLabel(thisChoice, label);
}
/** Adds a message consisting of one or more lines of text. */
public void addMessage(String text) {
addMessage(text, null, null);
}
/** Adds a message consisting of one or more lines of text,
which will be displayed using the specified font. */
public void addMessage(String text, Font font) {
addMessage(text, font, null);
}
/** Adds a message consisting of one or more lines of text,
which will be displayed using the specified font and color. */
public void addMessage(String text, Font font, Color color) {
theLabel = null;
if (text.indexOf('\n')>=0)
theLabel = new MultiLineLabel(text);
else
theLabel = new Label(text);
if (addToSameRow) {
c.gridx = GridBagConstraints.RELATIVE;
addToSameRow = false;
} else {
c.gridx = 0; c.gridy++;
c.insets = getInsets("".equals(text)?0:10, 20, 0, 0); // top, left, bottom, right
}
c.gridwidth = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.WEST;
c.fill = GridBagConstraints.HORIZONTAL;
if (font!=null) {
if (Prefs.getGuiScale()>1.0)
font = font.deriveFont((float)(font.getSize()*Prefs.getGuiScale()));
theLabel.setFont(font);
}
if (color!=null)
theLabel.setForeground(color);
add(theLabel, c);
c.fill = GridBagConstraints.NONE;
}
/** Adds one or two (side by side) text areas.
* @param text1 initial contents of the first text area
* @param text2 initial contents of the second text area or null
* @param rows the number of rows
* @param columns the number of columns
*/
public void addTextAreas(String text1, String text2, int rows, int columns) {
if (textArea1!=null) return;
Panel panel = new Panel();
Font font = new Font("SansSerif", Font.PLAIN, (int)(14*Prefs.getGuiScale()));
textArea1 = new TextArea(text1,rows,columns,TextArea.SCROLLBARS_NONE);
if (IJ.isLinux()) textArea1.setBackground(Color.white);
textArea1.setFont(font);
textArea1.addTextListener(this);
panel.add(textArea1);
if (text2!=null) {
textArea2 = new TextArea(text2,rows,columns,TextArea.SCROLLBARS_NONE);
if (IJ.isLinux()) textArea2.setBackground(Color.white);
textArea2.setFont(font);
panel.add(textArea2);
}
c.gridx = 0; c.gridy++;
c.gridwidth = GridBagConstraints.REMAINDER;
c.anchor = GridBagConstraints.WEST;
c.insets = getInsets(15, 20, 0, 0);
addToSameRow = false;
add(panel, c);
}
/**
* Adds a slider (scroll bar) to the dialog box.
* Floating point values are used if (maxValue-minValue)<=5.0
* and either defaultValue or minValue are non-integer.
* @param label the label
* @param minValue the minimum value of the slider
* @param maxValue the maximum value of the slider
* @param defaultValue the initial value of the slider
*/
public void addSlider(String label, double minValue, double maxValue, double defaultValue) {
if (defaultValue<minValue) defaultValue=minValue;
if (defaultValue>maxValue) defaultValue=maxValue;
int digits = 0;
double scale = 1.0;
if ((maxValue-minValue)<=5.0 && (minValue!=(int)minValue||maxValue!=(int)maxValue||defaultValue!=(int)defaultValue)) {
scale = 50.0;
minValue *= scale;
maxValue *= scale;
defaultValue *= scale;
digits = 2;
}
addSlider( label, minValue, maxValue, defaultValue, scale, digits);
}
/** This vesion of addSlider() adds a 'stepSize' argument.<br>
* Example: http://wsr.imagej.net/macros/SliderDemo.txt
*/
public void addSlider(String label, double minValue, double maxValue, double defaultValue, double stepSize) {
if ( stepSize <= 0 ) stepSize = 1;
int digits = digits(stepSize);
double scale = 1.0 / Math.abs( stepSize );
if ( scale <= 0 ) scale = 1;
if ( defaultValue < minValue ) defaultValue = minValue;
if ( defaultValue > maxValue ) defaultValue = maxValue;
minValue *= scale;
maxValue *= scale;
defaultValue *= scale;
addSlider(label, minValue, maxValue, defaultValue, scale, digits);
}
private int digits( double d ) {
if ( d == (int) d ) return 0;
String s = Double.toString(d);
s = s.substring(s.indexOf(".") + 1);
return s.length();
}
private void addSlider(String label, double minValue, double maxValue, double defaultValue, double scale, int digits) {
int columns = 4 + digits - 2;
if ( columns < 4 ) columns = 4;
if (minValue<0.0) columns++;
String label2 = label;
if (label2.indexOf('_')!=-1)
label2 = label2.replace('_', ' ');
Label theLabel = makeLabel(label2);
if (addToSameRow) {
c.gridx = GridBagConstraints.RELATIVE;
c.insets.bottom += 3;
addToSameRow = false;
} else {
c.gridx = 0; c.gridy++;
c.insets = getInsets(0, 0, 3, 0); // top, left, bottom, right
}
c.anchor = GridBagConstraints.EAST;
c.gridwidth = 1;
add(theLabel, c);
if (slider==null) {
slider = new Vector(5);
sliderIndexes = new Vector(5);
sliderScales = new Vector(5);
sliderDigits = new Vector(5);
}
Scrollbar s = new Scrollbar(Scrollbar.HORIZONTAL, (int)defaultValue, 1, (int)minValue, (int)maxValue+1);
slider.addElement(s);
s.addAdjustmentListener(this);
s.setUnitIncrement(1);
if (numberField==null) {
numberField = new Vector(5);
defaultValues = new Vector(5);
defaultText = new Vector(5);
}
if (IJ.isWindows()) columns -= 2;
if (columns<1) columns = 1;
//IJ.log("scale=" + scale + ", columns=" + columns + ", digits=" + digits);
TextField tf = new TextField(IJ.d2s(defaultValue/scale, digits), columns);
if (IJ.isLinux()) tf.setBackground(Color.white);
tf.addActionListener(this);
tf.addTextListener(this);
tf.addFocusListener(this);
tf.addKeyListener(this);
numberField.addElement(tf);
sliderIndexes.add(new Integer(numberField.size()-1));
sliderScales.add(new Double(scale));
sliderDigits.add(new Integer(digits));
defaultValues.addElement(new Double(defaultValue/scale));
defaultText.addElement(tf.getText());
tf.setEditable(true);
firstSlider = false;
Panel panel = new Panel();
GridBagLayout pgrid = new GridBagLayout();
GridBagConstraints pc = new GridBagConstraints();
panel.setLayout(pgrid);
pc.gridx = 0; pc.gridy = 0;
pc.gridwidth = 1;
pc.ipadx = 85;
pc.anchor = GridBagConstraints.WEST;
panel.add(s, pc);
pc.ipadx = 0; // reset
// text field
pc.gridx = 1;
pc.insets = new Insets(5, 5, 0, 0);
pc.anchor = GridBagConstraints.EAST;
panel.add(tf, pc);
c.gridx = GridBagConstraints.RELATIVE;
c.gridwidth = 1;
c.anchor = GridBagConstraints.WEST;
c.insets.left = 0;
c.insets.bottom -= 3;
add(panel, c);
if (Recorder.record || macro)
saveLabel(tf, label);
}
/** Adds a Panel to the dialog. */
public void addPanel(Panel panel) {
addPanel(panel, GridBagConstraints.WEST, addToSameRow ? c.insets : getInsets(5,0,0,0));
}
/** Adds a Panel to the dialog with custom contraint and insets. The
defaults are GridBagConstraints.WEST (left justified) and
"new Insets(5, 0, 0, 0)" (5 pixels of padding at the top). */
public void addPanel(Panel panel, int constraints, Insets insets) {
if (addToSameRow) {
c.gridx = GridBagConstraints.RELATIVE;
addToSameRow = false;
} else {
c.gridx = 0; c.gridy++;
}
c.gridwidth = 2;
c.anchor = constraints;
c.insets = insets;
add(panel, c);
}
/** Adds an image to the dialog. */
public void addImage(ImagePlus image) {
ImagePanel imagePanel = new ImagePanel(image);
addPanel(imagePanel);
if (imagePanels==null)
imagePanels = new Vector();
imagePanels.add(imagePanel);
}
/** Set the insets (margins), in pixels, that will be
used for the next component added to the dialog
(except components added to the same row with addToSameRow)
<pre>
Default insets:
addMessage: 0,20,0 (empty string) or 10,20,0
addCheckbox: 15,20,0 (first checkbox) or 0,20,0
addCheckboxGroup: 10,0,0
addRadioButtonGroup: 5,10,0
addNumericField: 5,0,3 (first field) or 0,0,3
addStringField: 5,0,5 (first field) or 0,0,5
addChoice: 5,0,5 (first field) or 0,0,5
</pre>
*/
public void setInsets(int top, int left, int bottom) {
topInset = top;
leftInset = left;
bottomInset = bottom;
customInsets = true;
}
/** Makes the next item appear in the same row as the previous.
* May be used for addNumericField, addSlider, addChoice, addCheckbox, addStringField,
* addMessage, addPanel, and before the showDialog() method
* (in the latter case, the buttons appear to the right of the previous item).
* Note that addMessage (and addStringField, if its column width is more than 8) use
* the remaining width, so it must be the last item of a row.
*/
public void addToSameRow() {
addToSameRow = true;
addToSameRowCalled = true;
}
/** Sets a replacement label for the "OK" button. */
public void setOKLabel(String label) {
okLabel = label;
}
/** Sets a replacement label for the "Cancel" button. */
public void setCancelLabel(String label) {
cancelLabel = label;
}
/** Sets a replacement label for the "Help" button. */
public void setHelpLabel(String label) {
helpLabel = label;
}
/** Unchanged parameters are not recorder in 'smart recording' mode. */
public void setSmartRecording(boolean smartRecording) {
this.smartRecording = smartRecording;
}
/** Make this a "Yes No Cancel" dialog. */
public void enableYesNoCancel() {
enableYesNoCancel(" Yes ", " No ");
}
/** Make this a "Yes No Cancel" dialog with custom labels. Here is an example:
<pre>
GenericDialog gd = new GenericDialog("YesNoCancel Demo");
gd.addMessage("This is a custom YesNoCancel dialog");
gd.enableYesNoCancel("Do something", "Do something else");
gd.showDialog();
if (gd.wasCanceled())
IJ.log("User clicked 'Cancel'");
else if (gd.wasOKed())
IJ. log("User clicked 'Yes'");
else
IJ. log("User clicked 'No'");
</pre>
*/
public void enableYesNoCancel(String yesLabel, String noLabel) {
this.yesLabel = yesLabel;
this.noLabel = noLabel;
yesNoCancel = true;
}
/** No not display "Cancel" button. */
public void hideCancelButton() {
hideCancelButton = true;
}
Insets getInsets(int top, int left, int bottom, int right) {
if (customInsets) {
customInsets = false;
return new Insets(topInset, leftInset, bottomInset, 0);
} else
return new Insets(top, left, bottom, right);
}
/** Add an Object implementing the DialogListener interface. This object will
* be notified by its dialogItemChanged method of input to the dialog. The first
* DialogListener will be also called after the user has typed 'OK' or if the
* dialog has been invoked by a macro; it should read all input fields of the
* dialog.
* For other listeners, the OK button will not cause a call to dialogItemChanged;
* the CANCEL button will never cause such a call.
* @param dl the Object that wants to listen.
*/
public void addDialogListener(DialogListener dl) {
if (dialogListeners == null)
dialogListeners = new Vector();
dialogListeners.addElement(dl);
if (IJ.debugMode) IJ.log("GenericDialog: Listener added: "+dl);
}
/** Returns true if the user clicked on "Cancel". */
public boolean wasCanceled() {
if (wasCanceled && !Thread.currentThread().getName().endsWith("Script_Macro$"))
Macro.abort();
return wasCanceled;
}
/** Returns true if the user has clicked on "OK" or a macro is running. */
public boolean wasOKed() {
return wasOKed || macro;
}
/** Returns the contents of the next numeric field,
or NaN if the field does not contain a number. */
public double getNextNumber() {
if (numberField==null)
return -1.0;
TextField tf = (TextField)numberField.elementAt(nfIndex);
String theText = tf.getText();
String label=null;
if (macro) {
label = (String)labels.get((Object)tf);
theText = Macro.getValue(macroOptions, label, theText);
}
String originalText = (String)defaultText.elementAt(nfIndex);
double defaultValue = ((Double)(defaultValues.elementAt(nfIndex))).doubleValue();
double value;
boolean skipRecording = false;
if (theText.equals(originalText)) {
value = defaultValue;
if (smartRecording) skipRecording=true;
} else {
Double d = getValue(theText);
if (d!=null)
value = d.doubleValue();
else {
// Is the value a macro variable?
if (theText.startsWith("&")) theText = theText.substring(1);
Interpreter interp = Interpreter.getInstance();
value = interp!=null?interp.getVariable2(theText):Double.NaN;
if (Double.isNaN(value)) {
invalidNumber = true;
errorMessage = "\""+theText+"\" is an invalid number";
value = Double.NaN;
if (macro) {
IJ.error("Macro Error", "Numeric value expected in run() function\n \n"
+" Dialog box title: \""+getTitle()+"\"\n"
+" Key: \""+label.toLowerCase(Locale.US)+"\"\n"
+" Value or variable name: \""+theText+"\"");
}
}
}
}
if (recorderOn && !skipRecording) {
recordOption(tf, trim(theText));
}
nfIndex++;
return value;
}
private String trim(String value) {
if (value.endsWith(".0"))
value = value.substring(0, value.length()-2);
if (value.endsWith(".00"))
value = value.substring(0, value.length()-3);
return value;
}
private void recordOption(Object component, String value) {
String label = (String)labels.get(component);
if (value.equals("")) value = "[]";
Recorder.recordOption(label, value);
}
private void recordCheckboxOption(Checkbox cb) {
String label = (String)labels.get((Object)cb);
if (label!=null) {
if (cb.getState()) // checked
Recorder.recordOption(label);
else if (Recorder.getCommandOptions()==null)
Recorder.recordOption(" ");
}
}
protected Double getValue(String text) {
Double d;
try {d = new Double(text);}
catch (NumberFormatException e){
d = null;
}
return d;
}
public double parseDouble(String s) {
if (s==null) return Double.NaN;
double value = Tools.parseDouble(s);
if (Double.isNaN(value)) {
if (s.startsWith("&")) s = s.substring(1);
Interpreter interp = Interpreter.getInstance();
value = interp!=null?interp.getVariable2(s):Double.NaN;
}
return value;
}
/** Returns true if one or more of the numeric fields contained an
invalid number. Must be called after one or more calls to getNextNumber(). */
public boolean invalidNumber() {
boolean wasInvalid = invalidNumber;
invalidNumber = false;
return wasInvalid;
}
/** Returns an error message if getNextNumber was unable to convert a
string into a number, otherwise, returns null. */
public String getErrorMessage() {
return errorMessage;
}
/** Returns the contents of the next text field. */
public String getNextString() {
String theText;
if (stringField==null)
return "";
TextField tf = (TextField)(stringField.elementAt(sfIndex));
theText = tf.getText();
if (macro) {
String label = (String)labels.get((Object)tf);
theText = Macro.getValue(macroOptions, label, theText);