File: ScatterPlotApplet.java

package info (click to toggle)
jcm 1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,340 kB
  • sloc: java: 14,629; makefile: 13
file content (363 lines) | stat: -rw-r--r-- 15,219 bytes parent folder | download | duplicates (3)
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
/**************************************************************************
* Copyright (c) 2001, 2005 David J. Eck                                   *
*                                                                         *
* Permission is hereby granted, free of charge, to any person obtaining   *
* a copy of this software and associated documentation files (the         *
* "Software"), to deal in the Software without restriction, including     *
* without limitation the rights to use, copy, modify, merge, publish,     *
* distribute, sublicense, and/or sell copies of the Software, and to      *
* permit persons to whom the Software is furnished to do so, subject to   *
* the following conditions:                                               *
*                                                                         *
* The above copyright notice and this permission notice shall be included *
* in all copies or substantial portions of the Software.                  *
*                                                                         *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,         *
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF      *
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  *
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY    *
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,    *
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE       *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                  *
*                                                                         *
* ----                                                                    *
* (Released under new license, April 2012.)                               *
*                                                                         *
*             David J. Eck                                                *
*             Department of Mathematics and Computer Science              *
*             Hobart and William Smith Colleges                           *
*             300 Pulteney Street                                         *
*             Geneva, NY 14456                                            *
*             eck@hws.edu                                                 *
*             http://math.hws.edu/eck                                     *
**************************************************************************/



import edu.hws.jcm.awt.*;
import edu.hws.jcm.data.*;
import edu.hws.jcm.draw.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.applet.Applet;

/**
 * A ScatterPlotApplet shows a scatter plot of data from a DataTableInput.
 * The user can enter the data in a two-column table that is shown in
 * the applet.  It is also possible to configure the applet with a menu
 * of file names.  These files, which must be in the same directory as
 * the Web page on which the applet appears, will appear in a menu.
 * A file can contain data for the table, with two numbers per line.
 * When the user loads the file, the data replaces the data in the table.
 */

public class ScatterPlotApplet extends Applet implements ActionListener {

   private Frame frame;       // If non-null, a separate window.
   private String frameTitle; // Title for the separate window.
   private Button launchButton;  // If non-null, then clicking this buttons opens a separate window.
   private String launchButtonName;  // Name for the launch button.
   
   private DataTableInput table;    //  The table for input of data.
   private ScatterPlot scatterPlot; //  The scatter plot of the data.
   private DisplayCanvas canvas;    //  The DisplayCanvas on which the plot is drawn.
   private Button loadFileButton;   //  When clicked, a data file is loaded.
   private Choice fileMenu;         //  Pop-up menu containing names of functions.
   private String[] fileNames;      //  Names of data files associated with menu entries.
   private Controller mainController;  // Controller from the main JCMPanel.

   /**
    * The init() method is called by the system to set up the applet. 
    * If the applet does not appear as a button, then init() creates the main panel of the applet
    * and calls setUpMainPanel to set it up.
    */
   public void init() {
      frameTitle = getParameter("FrameTitle"); // Get title to be used for separate window, if any.
      if (frameTitle == null) {
         frameTitle = "Scatter Plots";
         int pos = frameTitle.lastIndexOf('.');
         if (pos > -1)
            frameTitle =  frameTitle.substring(pos+1);
      }
      setLayout(new BorderLayout());
      int height = getSize().height;
      launchButtonName = getParameter("LaunchButtonName");
      if ( (height > 0 && height <= 50) || launchButtonName != null) {
              // Use a separater window and only show a button in the applet.
          if (launchButtonName == null)
               launchButtonName = "Launch " + frameTitle;
          launchButton = new Button(launchButtonName);
          add(launchButton, BorderLayout.CENTER);
          launchButton.addActionListener(this);
      }
      else {
             // Show the main panel in the applet, not in a separate window.
          add(makeMainPanel(), BorderLayout.CENTER);
      }
   }

   /*
    * Create the main panel of the applet.
    */ 
   public Panel makeMainPanel() {
   
      // Make the main panel
   
      JCMPanel panel = new JCMPanel(2);
      mainController = panel.getController();
      panel.setBackground(new Color(0,0,180));
      panel.setInsetGap(2);
      setLayout(new BorderLayout());
      
      // Make a DataInputTable with two columns
      
      table = new DataTableInput(null, 2);
      table.setColumnName(0, getParameter("ColumnName1", "X"));
      table.setColumnName(1, getParameter("ColumnName2", "Y"));
      table.setThrowErrors(true);
      if ( "yes".equalsIgnoreCase(getParameter("ShowColumnTitles","yes")))
         table.setShowColumnTitles(true);
      if ( "yes".equalsIgnoreCase(getParameter("ShowRowNumbers","yes")))
         table.setShowRowNumbers(true);
                                 
      // Make input boxes for getting expressions that can include
      // the variables associated with the table.  Initially, the 
      // expressions are just the column names.

      Parser parser = new Parser();
      table.addVariablesToParser(parser);
      ExpressionInput input1 = new ExpressionInput(table.getColumnName(0),parser);
      input1.setOnUserAction(mainController);
      ExpressionInput input2 = new ExpressionInput(table.getColumnName(1),parser);
      input2.setOnUserAction(mainController);
      
      // Make a scatter plot that graphs the first expressiong vs. the second expression.

      scatterPlot = new ScatterPlot(table, input1.getExpression(), input2.getExpression());
      if ( ! "yes".equalsIgnoreCase(getParameter("ShowRegressionLine","yes")))
        scatterPlot.setShowRegressionLine(false);
      if ( ! "yes".equalsIgnoreCase(getParameter("MissingValueIsError","yes")))
        scatterPlot.setMissingValueIsError(false);
        
      // Create the display canvas where the scater plot will be shown.

      canvas = new DisplayCanvas();
      canvas.add(new Axes());
      canvas.add(scatterPlot);
      mainController.setErrorReporter(canvas);
      
      // A compute button to recompute everything.
      
      ComputeButton computeButton = new ComputeButton("Update Display");
      computeButton.setOnUserAction(mainController);
      computeButton.setBackground(Color.lightGray);
      
      // A menu of files that can be loaded.  If no filenames are provided as
      // applet parameters, then menu is null.
      
      Panel menu = makefileMenu();
      
      // Lay out the components in the applet.
      
      JCMPanel inputPanel = null;
      Panel bottom = null;  //might not be a JCMPanel
      if ( "yes".equalsIgnoreCase(getParameter("UseExpressionInputs","yes"))) {
         inputPanel = new JCMPanel(1,2);
         inputPanel.setBackground(Color.lightGray);
         JCMPanel leftInput = new JCMPanel();
         leftInput.add(new Label("  Plot:  "), BorderLayout.WEST);
         leftInput.add(input1, BorderLayout.CENTER);
         inputPanel.add(leftInput);
         JCMPanel rightInput = new JCMPanel();
         rightInput.add(new Label(" versus: "), BorderLayout.WEST);
         rightInput.add(input2, BorderLayout.CENTER);
         inputPanel.add(rightInput);
         bottom = new JCMPanel(new BorderLayout(12,3));
         bottom.add(inputPanel, BorderLayout.CENTER);
         bottom.add(computeButton, BorderLayout.EAST);
      }
      
      if ( scatterPlot.getShowRegressionLine() && "yes".equalsIgnoreCase(getParameter("ShowStats","yes")) ) {
            // Make a display label to show some statistics about the data.
         DisplayLabel dl = new DisplayLabel(
               "Slope = #;  Intercept = #;  Correlation = #",
                new Value[] { scatterPlot.getValueObject(ScatterPlot.SLOPE), 
                              scatterPlot.getValueObject(ScatterPlot.INTERCEPT), 
                              scatterPlot.getValueObject(ScatterPlot.CORRELATION) }
            );
         dl.setAlignment(Label.CENTER);
         dl.setBackground(Color.lightGray);
         dl.setForeground(new Color(200,0,0));
         dl.setFont(new Font("Serif",Font.PLAIN,14));
         if (bottom != null) 
            bottom.add(dl, BorderLayout.SOUTH);
         else {
            bottom = new JCMPanel(new BorderLayout(12,3));
            bottom.add(dl, BorderLayout.CENTER);
            bottom.add(computeButton, BorderLayout.EAST);
         }
      }
      
      if (bottom == null) {
         if (menu != null)
            menu.add(computeButton, BorderLayout.EAST);
         else {
            bottom = new Panel();
            bottom.add(computeButton);
         }
      }
      
      panel.add(canvas, BorderLayout.CENTER);
      panel.add(table, BorderLayout.WEST);
      if (bottom != null)
         panel.add(bottom, BorderLayout.SOUTH);
      if (menu != null)
         panel.add(menu, BorderLayout.NORTH);
      else {
         String title = getParameter("PanelTitle");
         if (title != null) {
            Label pt = new Label(title, Label.CENTER);
            pt.setBackground(Color.lightGray);
            pt.setForeground(new Color(200,0,0));
            pt.setFont(new Font("Serif",Font.PLAIN,14));
            panel.add(pt, BorderLayout.NORTH);
         }
      }
         
      return panel;
      
   } // end makeMainPanel()
   
   
   private Panel makefileMenu() {
         // If the applet tag contains params named "File", "File1", "File2", ..., use
         // their values to make a file menu.  If the value of the param contains a ";",
         // then the first part, up to the ";", goes into the menu and the second part
         // is the name of the file.  If there is no ";", then the entire value is
         // shown in the menu and is also used as the name of the file.  The actual
         // files must be in the same directory as the Web page that contains the applet.
      Vector names = new Vector();
      fileMenu = new Choice();
      String file = getParameter("File");
      int ct = 1;
      if (file == null) {
         file = getParameter("File1");
         ct = 2;
      }
      while (file != null) {
         file = file.trim();
         int pos = file.indexOf(";");
         String menuEntry;
         if (pos == -1)
            menuEntry = file;
         else {
            menuEntry = file.substring(0,pos).trim();
            file = file.substring(pos+1).trim();
         }
         names.addElement(file);
         fileMenu.add(menuEntry);
         file = getParameter("File" + ct);
         ct++;
      }
      if (names.size() == 0) {
         fileMenu = null;
         return null;
      }
      else {
         fileNames  = new String[names.size()];
         for (int i = 0; i < names.size(); i++)
            fileNames[i] = (String)names.elementAt(i);
         Panel p = new Panel();
         p.setBackground(Color.lightGray);
         p.setLayout(new BorderLayout(5,5));
         p.add(fileMenu,BorderLayout.CENTER);
         loadFileButton = new Button("Load Data File: ");
         loadFileButton.addActionListener(this);
         p.add(loadFileButton,BorderLayout.WEST);
         fileMenu.setBackground(Color.white);
         return p;
      }
   }
   
   private void doLoadFile(String name) {
        // Load the file from the same directory as the Web page and put the data
        // from the file into the table.  The file should contain two numbers on
        // each line.
      InputStream in;
      try {
         URL url = new URL(getDocumentBase(), name);
         in = url.openStream();
      }
      catch (Exception e) {
         canvas.setErrorMessage(null,"Unable to open file named \"" + name + "\": " + e);
         return;
      }
      Reader inputReader = new InputStreamReader(in);
      try {
         table.readFromStream(inputReader);
         inputReader.close();
      }
      catch (Exception e) {
         canvas.setErrorMessage(null,"Unable to get data from file \"" + name + "\": " + e.getMessage());
         return;
      }
      mainController.compute();
   }

   /**
    *  Respond when user clicks a button; not meant to be called directly.
    *  This opens and closes the separate window.
    */ 
   synchronized public void actionPerformed(ActionEvent evt) {
      Object source = evt.getSource();
      if (loadFileButton != null && source == loadFileButton) {
         doLoadFile( fileNames[fileMenu.getSelectedIndex()] );
      }
      else if (source == launchButton && launchButton != null) {
            // Open or close separate frame.
         launchButton.setEnabled(false);
         if (frame == null) {
            frame = new Frame(frameTitle);
            frame.add(makeMainPanel());
            frame.addWindowListener( new WindowAdapter() {
                  public void windowClosing(WindowEvent evt) {
                     frame.dispose();
                  }
                  public void windowClosed(WindowEvent evt) {
                     frameClosed();
                  }
               } );
            frame.pack();
            frame.setLocation(50,50);
            frame.show();
            launchButton.setLabel("Close Window");
            launchButton.setEnabled(true);
         }
         else {
            frame.dispose();
         }
      }
   }
   
   synchronized private void frameClosed() {
        // respond when separate window closes.
      frame = null;
      launchButton.setLabel(launchButtonName);
      launchButton.setEnabled(true);
   }
   
   /**
    *  Return the applet parameter with a given param name, but if no
    *  such applet param exists, return a default value instead.
    */
   protected String getParameter(String paramName, String defaultValue) {
       String val = getParameter(paramName);
       return (val == null)? defaultValue : val;
   }
   
} // end class ScatterPlotApplet