Chapter 9: Dialog Windows

Question 9.1: How can I prompt the user to select columns to be used in an analysis?

Question 9.2: How can I stop a script if a user clicks the Cancel button in a dialog window?

Question 9.3: How can I prompt the user to select a file in a specific directory? I want to display only those files of a specific type, such as text.

Question 9.4: Can a wildcard character be used to open several data tables that contain specific characters in the filename?

Question 9.5: How can I can prompt the user for information, and then use that value in the SQL string for extracting data from a database?

Question 9.6: How can I prompt the user to select starting and ending dates, as well as a title to be used in a report?

Question 9.7: How can I populate a Combo Box based upon what a user selects in another Combo Box, and then generate a subset table that meets the selection criteria?

Question 9.8: How can I use Column Switcher to affect multiple graphs in the same window?

Question 9.9: Is it possible to show or hide a display box based upon a user’s prior selection in the same window?

Question 9.10: Why does the Excel Wizard open when I import data from my New Window?

Question 9.11:  When I try to limit the columns shown in a Col List Box to numeric, no columns appear.  Why?

 

 

Question 9.1: How can I prompt the user to select columns to be used in an analysis? 

 

Solution 9.1:

A quick way to build a dialog that will allow a user to select columns from a data table is to use the Column Dialog() function.  The design and formatting of the window is built into Column Dialog().  The result is a modal window that includes all the columns in the data table.

/* Open the sample data table, Big Class */

dt = Open( "$SAMPLE_DATA/Big Class.jmp" ); 

 

/* Query the user for a single column */

cdlg = Column Dialog(

    yCol = ColList( "Y, Response", MinCol( 1 ), MaxCol( 1 ) ),

    xCol = ColList( "X, Factor", MinCol( 1 ), MaxCol( 1 ) )

); 

 

/* Unload the values from the Column Dialog */

my_Y = cdlg["yCol"][1];

my_X = cdlg["xCol"][1];

 

/* Use the column selections in an analysis */ 

fit = Fit Y By X( Y( my_Y ), X( my_X ) );

Remember from chapter 7 that the value returned by Column Dialog() must be unloaded before it can be used in the analysis. Also, there are multiple ways to unload the values from Column Dialog(). See the “Column Dialog()” section in chapter 7 for an alternate method.

More information regarding constructors that are specific to Column Dialog() can be found in the “Modal Dialogs” section of the “Display Trees” chapter in the Scripting Guide.

Result 9.1:

Figure 9.1 Column Dialog Window with One Column Selected

Figure 9.1 Column Dialog Window with One Column Selected

Figure 9.2 Oneway of Selected Column

Figure 9.2 Oneway of Selected Column

 

Question 9.2: How can I stop a script if a user clicks the Cancel button in a dialog window?  

Solution 9.2:

Prompting the user for information is a fairly common scripting objective.  In order to prevent your script from generating errors, the script should stop executing if the user clicks the Cancel button or closes the window.

The following example demonstrates a modal New Window() to prompt the user for information. If the OK button is clicked, the value of ageVar is shown in the log. If the Cancel button is clicked or if the user closes the window, Cancelled! is printed in the log, and the script stops.

/* Create a modal New Window to query the user */

ageDlg = New Window( "How old are you?",

    <<Modal,

    <<Return Result,

    LineupBox( NCol( 1 ), Spacing( 5 ),

            Text Box( "How old are you?" ),

            ageVar = Number Edit Box( 29 )

    ),

    H List Box( Button Box( "OK" ), Button Box( "Cancel" ) )

);

 

/* Test the result: If button = -1, the Cancel button was clicked */

If( ageDlg["button"] == -1,

    Throw( "Cancelled!" );

);

 

/* Show variable result in log if OK was clicked */

Show( ageDlg["ageVar"] );

If the user clicks the Cancel button or closes the window, the Throw() function stops further execution of the script. The last line of the example script is only executed if the user clicks the OK button in the modal New Window().

Result 9.2:

Figure 9.3 Dialog Window Where Cancel Is Clicked

Figure 9.3 Dialog Window Where Cancel Is Clicked  

Figure 9.4 Log After Cancel Was Clicked

Figure 9.4 Log After Cancel Was Clicked

Question 9.3: How can I prompt the user to select a file in a specific directory? I want to display only those files of a specific type, such as text. 

 

Solution 9.3:

As we discussed in chapter 7, you can use the Pick File() function to allow the user to navigate to and select a file.  In addition, you can limit the files shown by specifying the file types in the third argument of the Pick File() function.

/* Prompt the user to select a TXT or CSV file */

textFile =Pick File(

    "Select a Text File",

    "$SAMPLE_IMPORT_DATA",

    {"TXT Files|txt", "CSV Files|csv"},

    1,

    0

); 

 

/* Open the file the user selected and give it a reference */

dt = Open( textFile );

More information about Pick File() and its arguments can be found in the “File and Directory Operations” section of the “Programming Methods” chapter in the Scripting Guide.

Result 9.3:

Figure 9.5 File Selection

Figure 9.5 File Selection

Question 9.4: Can a wildcard character be used to open several data tables that contain specific characters in the filename? 

Solution 9.4:

On Windows operating systems, you can use wildcards in an Open dialog to filter the list of files to select from.

Figure 9.6 File Dialog Using Wildcards

However, that is not a programmatic approach. Unfortunately, there are no available wildcard characters that can be used for limiting files by a portion of the name using a script.

Instead, you can use the Pick Directory() function to prompt the user for a directory and extract the files using the Files In Directory() function. Finally, you can loop through each file name and keep only the files with the specified character string in the name.

In the following example, we want to open any file that contains the characters COMPARE in the file name. The Uppercase() function is used to ensure that the case of the actual filename is not a differentiating factor in the comparison of the search term, COMPARE.

/*  Prompt the user to select a directory */

path = Pick Directory(

    "Select the Samples > Data Directory ", "$SAMPLE_DATA"

);

 

/* Obtain a list of all the files in the directory */

listOfFiles = Files In Directory( path );

 


 

/* Loop through each item in the list */

For( i = N Items( listOfFiles ), i >= 1, i--,

    /* If the filename contains the desired string, open the file */

    If( Contains(Uppercase( listOfFiles[i] ), "COMPARE" ),

            Open( path || listOfFiles[i] ),

            /* Else, remove the file name from the list */

            Remove From( listOfFiles, i )

    )

);

In the For() loop used in the example, notice that the loop starts at the end of the list and is incremented by subtracting 1 from the increment variable.  Why did we do this instead of starting with the first item in the list?  Because we are removing items from the list, the number of items in the list is expected to change.  By starting at the end of the list, our index is unaffected by removing an item from the list.

Result 9.4:

Figure 9.7  Pick Directory

Figure 9.7 Pick Directory

Figure 9.8 Tables Opened That Contain “COMPARE” in the Filename

 Figure 9.8 Tables Opened That Contain “COMPARE” in the Filename

Question 9.5: How can I can prompt the user for information, and then use that value in the SQL string for extracting data from a database? 

 

Solution 9.5:

When connecting to a database, the SQL query is passed as a string to the data source.  There are multiple ways to insert the value from a JSL variable into a string.

In the following example, we prompt the user for information with a modal New Window(). That value is then concatenated into the SQL query stored in sqlStr.  You can also use Eval Insert() to evaluate the variable within carets (^).  This method is shown in the commented section marked /** Alternate method **/.  The sqlStr string variable is later used as the SQL query specified in second argument for the Open Database() command. 

/* Prompt user for a name to be used in the SQL query */

nw = New Window("Enter Name",

    <<Modal,

    Lineup Box( Ncol( 2 ), Spacing( 5 ),

            Text Box("Enter your first name: "),

            teb = TextEdit Box( "Robert" )

    ),

    Button Box("OK", fname = teb << Get Text )

);

 

/* Stop if user closed the window */

If(nw["Button"]==-1, Throw());

 

/* Create a string that contains the SQL concatenated

with the user-specified value from the dialog */

sqlStr = "SELECT * FROM [dbitest].[Big_Class] WHERE dbitest.Big_Class.name = '" || Uppercase(fname) || "'";

 

/** Alternate method **/

/* Use Eval Insert() with carets (^) around the user

specified value from the dialog */

//sqlStr = Eval Insert( "SELECT * FROM [dbitest].[Big_Class] WHERE //dbitest.Big_Class.name = '^Uppercase(fname)^'");

 

/* Use the variable as the second argument */

dt = Open Database( "Connect Dialog", sqlStr );

Notice, the first argument in the Open Database() function is listed as "Connect Dialog". You might choose to include the actual connection information for your data source. If you run this code, you are prompted to select a data source that is available on your machine. For this example, we opened a table that has the same layout and data as the Big Class sample data table stored in an SQL Server database.

Detailed information about the Open Database() function can be found in the “Database access” section of the “Extending JMP” chapter in the Scripting Guide.

Result 9.5: 

Figure 9.9  Dialog Window

Figure 9.9 Dialog Window

Figure 9.10  Select SQL Server Data Source

Figure 9.10 Select SQL Server Data Source

Figure 9.11  Imported Data That Honored the User Selection

Figure 9.11 Imported Data That Honored the User Selection

 

Question 9.6: How can I prompt the user to select starting and ending dates, as well as a title to be used in a report? 

 

Solution 9.6:

When you provide a datetime format for a Number Edit Box, you get a little calendar icon that appears inside the left edge of the Number Edit Box.  When the user clicks the icon, a neat pop-up calendar appears in which they can easily select a date and time value. The value stored in the Number Edit Box is a JMP datetime value.

An alternative is to use the Calendar Box() instead of the Number Edit Box() to collect the dates, as Option #2 shows.

In the following example, we demonstrate using a Lineup Box to arrange the text and input display boxes in two columns.  The button script captures all the user’s input in variables for later use.

Option #1:

/* Create a modal user dialog */

New Window( "Select Date Range:",

    <<Modal,

    /* Arrange display boxes in two columns */

    Lineup Box( N Col( 2 ), Spacing( 10 ),

        /* Prompt for a report title */

            Text Box( "Report Title:" ),

            teb = Text Edit Box( "Weekly Report" ),

            /* Prompt for start and end dates */

            Text Box( "Start Date:" ),

            Text Box( "End Date:" ),

            /* Number Edit Box with a calendar pop-up */

            neb1 = Number Edit Box(

                    Today() - In Weeks( 1 ),

                    12,

                    <<Set Format( Format( "m/d/y", 12 ) )

            ),

            /* Number Edit Box with a calendar pop-up */

            neb2 = Number Edit Box(

                    Today(),

                    23,

                    <<Set Format( Format( "m/d/y", 12 ) )

            ),

            /* Placeholder so OK button is on right */

            Text Box( "" ),

            /* OK button captures the values */ 

            Button Box( "OK",

                    rtitle = teb << Get Text;

                    sdate = neb1 << Get;

                    edate = neb2 << Get;

            )

    )

);

 

Option #2:

/* Create a modal user dialog */

New Window( "Select Date Range:",

    <<Modal,

    /* Arrange DisplayBoxes in two columns */

    Lineup Box( N Col( 2 ), Spacing( 10 ),

        /* Prompt for a report title */

            Text Box( "Report Title:" ),

            teb = Text Edit Box( "Weekly Report" ),

            /* Prompt for start and end dates */

            Text Box( "Start Date:" ),

            Text Box( "End Date:" ),

            /* Calendar Box with a calendar pop-up for Start Date */

            cal1 = Calendar Box(),

            /* Calendar Box with a calendar pop-up for End Date */

            cal2 = Calendar Box(),

            /* Placeholder so OK button is on right */

            Text Box( "" ),

            /* OK button captures the values */ 

            Button Box( "OK",

                    rtitle = teb << Get Text;

                    sdate = cal1 << Get Date;

                    edate = cal2 << Get Date;

            )

    )

);

 

Result 9.6:

Figure 9.12 Modal User Dialog for Option 1

Figure 9.12 Modal User Dialog for Option 1

Figure 9.13 Modal User Dialog with Calendar Pop-Up Displayed with Option 1

Figure 9.13 Modal User Dialog with Calendar Pop-Up Displayed with Option 1

Figure 9.14 Modal User Dialog for Option 2

Figure 9.14 Modal User Dialog for Option 2 

 

Question 9.7: How can I populate a Combo Box based upon what a user selects in another Combo Box, and then generate a subset table that meets the selection criteria? 

 

Solution 9.7: 

This example prompts the user to select a make of cars.  Based on the selection, another Combo Box is populated with the available models by the selected auto manufacturer.  When the OK button is clicked, a subset table is generated that contains the data that meets the selection criteria with all columns included.

We’ve included the Set Function() option in the first Combo Box() section to demonstrate how it can be used to self-reference the display box.  See the embedded comments for details about what each section is doing. 

/* Open the sample data table invisibly */

dt = Open( "$SAMPLE_DATA/Cars 1993.jmp", invisible );

 

/* Obtain a list of the unique values in the Manufacturer column */

Summarize( dt, autoMaker = By( :Manufacturer ) );

 

/* Insert an empty value at the beginning of the list */

Insert Into( autoMaker, "<Select>", 1 );

 

/* Use New Window() to create a non-modal dialog to display

   manufacturer and model for user to choose */

nw = New Window( "Choose Models by Manufacturer",

    V List Box(

        Align("right" ), //Align button to the right side

        hb = H List Box( //Arrange Panel Boxes side by side

           Panel Box( "Select a Manufacturer",

                select1 = Combo Box(

                    autoMaker,

                   /* Function runs when a change in selection is made */

                    <<Set Function

                       //Allows self referencing using 'this'

                       Function( {this},

                           /* Find corresponding rows in the table */

                            selManufacturer = this << Get Selected;

                            r = dt << Get Rows Where( :Manufacturer == selManufacturer );

                           /* Update second ComboBox with models

                           for the selected manufacturer */

                            cbModel << Set Items( dt:Model[r] );

                        )

                    )

                )

            ),

           /* Initial PanelBox for selecting a model */

            pb = Panel Box( "Choose a Model", cbModel = Combo Box( " " ) )

        ),

        /* When the user clicks OK, a subset table is generated based

        upon the user selections and the window is closed */

        Button Box( "OK",

           /* Find corresponding rows for selected model */

            rs = dt << Get Rows Where( :Model == (cbModel << Get Selected) );

           /* Create subset with only the desired manufacturer/model */

            subdt = dt << Subset(

                Rows( rs ),

                Selected Columns Only( 0 ),

                Output Table Name( "Vehicle Details" )

            );

            nw << Close Window;

        )

    )

);

In this sample script, the user is being prompted to select a vehicle manufacturer. After that selection is made, JMP populates another Combo Box with the models produced by the selected manufacturer. Further, when the user clicks the OK button to dismiss the window, JMP produces a subset data table that contains the data for the selected manufacturer and model.

Result 9.7:

Figure 9.15  New Window Showing Only the Cadillac Models

Figure 9.15 New Window Showing Only the Cadillac Models

Figure 9.16  Data Table Subset of Only Cadillac DeVille

Figure 9.16 Data Table Subset of Only Cadillac DeVille

 

Question 9.8: How can I use Column Switcher to affect multiple graphs in the same window?

 

Solution 9.8:

Column Switcher is a nice feature that enables you to change analysis columns without having to re-create the analysis for each column. At this time, Column Switcher is limited to changing one analysis column in one graph. With a little bit of scripting, you can still get the desired effect but without using Column Switcher.

The following example demonstrates a custom New Window with a list of selectable columns and two analyses that are updated based upon the column selected by the user.  The Distribution and Graph Builder will remain live, so histogram bars can be clicked to select rows in the data table.

/* Open the sample data table, Candy Bars */

dt = Open( "$SAMPLE_DATACandy Bars.jmp", Invisible );

 

/* Create a function for actions to occur when a column is selected */

multipleColSwitch = Function( {col},

    vb << Delete //Delete previous VlistBox

    hb << Append //Append new VListBox

        vb = V List Box //Container for two analyses

            dist = dt << Distribution(

               Continuous Distribution( Column( col[1] ) ),

                Horizontal Layout( 1 )

            ),

            gb = dt << Graph Builder(

                Size( 537, 464 ),

                Show Control Panel( 0 ),

                Variables( X( :Brand ), Y( Column( col[1] ) ) ),

                Elements( Points( X, Y, Legend( 11 ),

                    Summary Statistic( "Median" ), Error Bars( "Range" ) ) ),

                SendToReport(

                    Dispatch(

                        {},

                       "Brand",

                        ScaleBox,

                        {Label Row( {Lower Frame( 1 ),

                            Tick Mark Style( "Long Divider" )} )}

                    )

                )

            )

        )

    );

);

 

/* Create a New Window containing columns and analyses */

nw = New Window( "Test",

    hb = H List Box //Container to place column list beside analyses

        Outline Box( "Select a column:",  

           /* Insert a ColListBox containing the continuous columns */

            clb = Col List Box(dt,

                All,

                MaxSelected(1 ),

               /* Nlines calculation = number of continuous columns +1 */

                Nlines( N Items( dt << Get Column Names( "Continuous" ) ) + 1 ),

                <<Set Analysis Type( "Continuous" ),

               /* Actions to be taken when a column is selected */

                colSelected = clb << Get Selected;

               If( N Items( colSelected ) == 1,

                    multipleColSwitch( colSelected )

                );

            )

        ),

        vb = V List Box() //Initial VlistBox

    )

);

Note: Included in the Jump into JMP Scripting Add-In is an extra script that includes all of the preceding code, plus an animation feature.

Result 9.8:

Figure 9.17  Initial Window of Column Names

Figure 9.17 Initial Window of Column Names  

 

Figure 9.18  Live Analyses of Selected Column

Figure 9.18 Live Analyses of Selected Column  

 

Question 9.9: Is it possible to show or hide a display box based upon a user’s prior selection in the same window?

Solution 9.9:

In this example, we demonstrate showing a ListBox of ice cream flavors only if the ice cream Check Box item is selected.  When the item is deselected, the ListBox becomes hidden.

/* Establish a list of ice cream flavors */

iceCreamFlavors = {"Butter Pecan", "Chocolate", "Coffee", "Cookie Dough", "Cookies 'N Cream", "Mint Chocolate Chip", "Maple Walnut", "Neopolitan", "Rocky Road", "Strawberry", "Vanilla"};

 

/* Create a function to handle the conditional visibility of the ListBox containing the ice cream flavor choices */

selectFxn = Function( {cb, item},

    If(

        /* If ice cream is checked, show the flavor choices */

        item == 1 & cb << Get( item ) == 1, lbIC << Visibility( "Visible" ),

        /* If ice cream is NOT checked, hide the flavor choices */

        item == 1 & cb << Get( item ) == 0, lbIC << Visibility( "Hidden" )

    )

);

 

/* Create a user interface to prompt the user */

nw = New Window( "Summer Treats",

    /* Visual enhancement: Adds a border around the contents */

    Border Box( Left( 10 ), Right( 10 ), Top( 10 ), Bottom( 10 ), Sides( 15 ),

        V List Box //Arranges the Text Box and Lineup Box vertically

           Text Box(

               "Please Select Your Favorite !nSummertime Treat:",

                <<Set Font Size( 14 ),

                <<Font Color( "Blue" )

            ),

           /* Arrange the CheckBox and ListBox side by side with some padding */

           Lineup Box( N Col( 2 ), Spacing( 10 ),

               Check Box(

                    {"Ice Cream", "Fruit"}, //CheckBox options

                   /* Function call runs each time an item is clicked and

                   allows access to itself (this) and the index (icheck) */

                    <<SetFunction(

                       Function( {this, icheck}, selectFxn( this, icheck ) )

                    )

                ),

               /* Visual enhancement: Adds text and a border */

                lbIC = Panel Box( "Ice Cream Flavors",

                   /* Allow selection of one flavor */

                   List Box( iceCreamFlavors, Max Selected( 1 ) ),

                   /* Hides the Panel Box */

                    <<Visibility( "Hidden" )

                )

            )

        )

    )

);

You could change the Visibility setting to "Collapse", as well.  We selected "Hidden" so that the size of the window is not adjusted for the appearance or disappearance of the ListBox.

Result 9.9

Figure 9.19 Treat Selection Dialog

Figure 9.19 Treat Selection Dialog

 

Question 9.10: Why does the Excel Wizard open when I import data from my New Window?

 

Solution 9.10:

On the General preference group (File Preferences), the default setting for the Excel Open Method is Use Excel Wizard.  Although the Excel Wizard is a very nice addition to JMP, you might want to just open the Excel file when running a script from a custom dialog window. 

When running a script, JMP is in batch mode.  For example, if you have an Open() function with the path to an Excel file as the argument, JMP opens the file. Any messaging appears in the log. However, when the script is associated with an interactive feature, such as a Button Box, JMP switches to interactive mode where all messaging is presented interactively. The user must click the button in order for the script to be executed.  Therefore, JMP is in interactive mode and the Excel Wizard appears.

The Batch Interactive() function can be used in your custom dialog’s Button Box script to ensure that JMP just opens the Excel file rather than presenting the user with the Excel Wizard, assuming default preference settings.

Note: This solution uses an experimental function called Batch Interactive().  Since the function is considered experimental, it is not included in the JMP documentation or Scripting Index. Although usage of this function is not supported, we are not aware of any issues that are attributed to the usage of Batch Interactive().

/* Opens the Excel worksheet */

New Window( "My Custom Dialog",

    Lineup Box( N Col( 1 ), Spacing( 5 ),

            Text Box( "When you are ready, please click: " ),

            Button Box( "Open Grouped Team Results",

                    Batch Interactive( 1 );  //Batch

                    Open(

                            "$SAMPLE_IMPORT_DATATeam Results.xlsx",

                            Worksheets("Grouped Team Results" ),

                            Worksheet Settings(

                                    1,

                                    Has Column Headers( 1 ),

                                    Number of Rows in Headers( 1 ),

                                    Headers Start on Row( 3 ),

                                    Data Starts on Row( 4 ),

                                    Data Starts on Column( 1 )

                            )

                    );

                    Batch Interactive( 0 );  //Interactive

            )

    )

);

Result 9.10:

Figure 9.20 Custom Dialog with Button

Figure 9.20 Custom Dialog with Button

Figure 9.21 Imported Excel File

Figure 9.21 Imported Excel File

 

Question 9.11:  When I try to limit the columns shown in a Col List Box to numeric, no columns appear.  Why?

 

Solution 9.11:

The Col List Box can either show columns from a data table or be a receiver of selected columns.  The first argument for Col List Box is a data table reference.  It is the second argument that determines whether the Col List Box will show columns or receive columns.  The options are as follows:

        "All" – Using this argument causes all columns from the data table to be available to appear. 

        "Numeric" – Using this argument causes the Col List Box to be a receiver of only numeric columns.

        "Character" – Using  this argument causes the Col List Box to be a receiver of only character columns.

To limit the columns that appear from the data table, you can use the <<Set Data Type and << Set Analysis Type options. 

/* Open a sample data table */

dt = Open( "$SAMPLE_DATAFitness.jmp" );

 

/* Create a window to prompt the user to select columns */

nw = New Window( "Launch Dialog",

   <<Modal,

   V List Box(

      Align( "right" ),

      H List Box(

         Panel Box( "Select Columns",

           /* Show only numeric columns from the table */

            clb = ColListBox( dt, all, <<Set Data Type( "Numeric" ) )

         ),

         Panel Box( "Cast Selected Columns into Roles",

           Lineup Box( N Col( 2 ), Spacing( 5 ),

              Button Box( "X, Treatment", clbX << Append( clb << Get Selected ) ),

              /* Receive at least 1 numeric column */

               clbX = Col List Box( "Numeric", MinItems( 1 ), MaxItems( 2 ), nlines( 2 )),

              Button Box( "Y, Response", clbY << Append( clb << Get Selected ) ),

              /* Receive at least 1 numeric column */

               clbY = Col List Box( "Numeric", MinItems( 1 ), MaxItems( 2 ), nlines( 2 )),

              Button Box( "Remove",

                  clbX << Remove Selected;

                  clbY << Remove Selected;

               )

            )

        )

    ),

     H List Box(

        Button Box( "OK",

          /* Retrieve the selected items as column references */

           xVars = clbX << Get Items("Column Reference" );

           yVars = clbY << Get Items("Column Reference" );

         ),

         Button Box( "Cancel" )

     )

  )

);

TIP:  When you use the optional "Column Reference" argument for the Get Items message, the result is a list of column references instead of a list of column names as strings.

Result 9.11:

Figure 9.22 New Window Showing Numeric Columns

Figure 9.22 New Window Showing Numeric Columns

 

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset