Or rather, my program does. I'm supposedly revising someone else's working code, but the stuff I compile doesn't do quite the same thing the packaged version they did... not sure whether it's a version difference, or a compiler difference (I used both JDK 1.3.1 and JBuilder 2005) or a computer difference (In Java? Heaven forbid!) or the problem exists between chair and keyboard. ;)
The current problem I'm trying to address is a keyboard shortcuts class. It's being constructed, and attached to a Base (extends JWindow) class, and the Base is focusable, visible, and set as having focus, but none of the keyboard shortcuts respond. In fact, I have a System.out.println statement at the very start of the overridden KeyTyped class which doesn't print, even when I'm sure that I typed keys.
There's a program selector window that starts various different versions of Base, and for reasons unknown, after each subprogram starts, the program selector window pops up again (which is certainly not how the packaged version works. Even when I click on the window with the program I'm working with, the program selector comes to the front again. I minimize it to do the work with the subprogram, but I think it might still be grabbing the focus while minimized.
How would I determine who has focus, let alone make sure that Base keeps it until it's done? What else do you need to know?

hi
can you attach necessary source code so that any body can run on their system and reply you back with their suggessions?
Regards
Srinivas

hi
can you attach necessary source code so that any body can run on their system and reply you back with their suggessions?
Regards
Srinivas

Well, I was hoping to avoid that; there's quite a lot of it...
Apologies in advance for the lack of commentary and the level of twistiness. I didn't write any of it to start off with, and am still trying to trim it down to something recognizable.
There's a y class with the main in it that calls the programselector.

/** Class for window used during tests
 *  Takes care of initiating tests, drawing tests, and
 *  cleaning up after test ends
 **/

package yerkes;

import javax.swing.*;
import java.awt.Color;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.util.*;
import java.awt.Graphics;
import java.io.*;
import javax.sound.sampled.*;


/**
 *
 * @author  Pearce Peck-Walden
 *
 **/
class Base extends JWindow {

  public String Tester, imageDirectory, monkeyid, dbHost;
  public boolean isDB, isSettingUp, written;
  public KeyEvent buttonPress;
  public int card, isBetween, correction, readytobypass;
  public int[][] customGrid;
  public Object[][] customImages;
  public String[] imageNames;
  private int skipInitial;
   private program1aHandler p1a;
   private program1bHandler p1b;
   private program2aHandler p2a;
   private program2bHandler p2b;
   private program3aHandler p3a;
   private program3bHandler p3b;
   private program4Handler p4;
   private program5Handler p5;
   private program6Handler p6;
   private program7Handler p7;
   private program8Handler p8;
   private startHandler sh;
   private Vector theImages;
   private JFrame tWindow;
   private int number, trials, customSize, baseline;
   private ImageIcon test;
   private int count, theC, countValid, pr, csst, reward, comPort, time, delay, customShift, customNumberStimuli;
   private int theX, theY, theX2, theY2, w, h, swap, numberOfImages, width, height, attention;
   protected int started;
   private java.util.Timer t;
   private String Date, Id,  prog, size;
   private float[] delays;
   private FileOutputStream outputFile = null;
   private PrintWriter outputStream = null;
   private Color[] colors = { Color.black, Color.blue, Color.gray, Color.green,  Color.orange, Color.pink,
     Color.yellow, Color.red, Color.white, new Color( 128, 64, 0 ), Color.cyan, Color.magenta, new Color( 153, 0, 153 ),
     Color.red, Color.green };
   private int[] theXs;
   private int[] theYs;
   private int[] csstData;
   private float iti;
   private Clip correctSound, incorrectSound;
   private ImageIcon asterix;
   private ImageIcon ii1, ii2;
   private BufferedImage buf;
   protected Graphics g2;
   private String[] customTargets;
   private boolean isProgressiveDelays;

   /** Creates new Base */
   public Base(Vector images, JFrame window, int program, String p, int theDelay,
               int tallow, String date, String id, String tester, int tr, float[] d, String outFile,
               String imageDir, String screenSize, int c, int v, int fr, String ititemp, String VD, String VT,
               int at, int v2, int rgb, int port, int cursor, int crd, Clip CS, Clip IS, String db, String custom1,
               String custom2, String custom3, String custom4, int stim, int shfts, int progDel, int corProc ) {

     if ( progDel == 0 ) isProgressiveDelays = true;
     else isProgressiveDelays = false;
     isBetween = 0;
     customTargets = new String[4];
     skipInitial = 0;
     customTargets[0] = custom1;
     customTargets[1] = custom2;
     customTargets[2] = custom3;
     customTargets[3] = custom4;
     customShift = shfts;
     customNumberStimuli = stim + 2;
     card = crd;
     theImages = images;
     tWindow = window;
     number = program;
     readytobypass = 0;
     prog = p;
     setBackground(Color.black);
     Date = date;
     Id = id;
     monkeyid = id;
     dbHost = db;
     Tester = tester;
     trials = tr;
     time = tallow;
     delays = d;
     delay = theDelay;
     size = screenSize;
     imageDirectory = imageDir;
     count = 0;
     swap = 0;
     numberOfImages = 1;
     theC = c;
     countValid = v;
     pr = fr;
     csst = v2;
     try{ iti = Float.parseFloat(ititemp); } catch (Exception e) {}
     attention = at;
     t = new java.util.Timer();
     correctSound = CS;
     incorrectSound = IS;
     comPort = port;
     reward = rgb;
     correction = corProc;
     isSettingUp = written = false;

     if ( dbHost.equals("")) {
       isDB = false;
     }
     else {
       isDB = true;
     }


     if(reward != 0)
     {
       com.setTime(Float.parseFloat(VD), Float.parseFloat(VT));
       usbHandler.setTime(Float.parseFloat(VD), Float.parseFloat(VT));
     }

       started = -1;
       asterix = new ImageIcon ( getClass().getResource("asterix.jpg") );
       if(cursor == 0)
       {
         this.setCursor( Toolkit.getDefaultToolkit().createCustomCursor(
           new ImageIcon ( getClass().getResource("cursor.gif")).getImage(),
           new Point(0,0),""));
       }


//If there is an output file, open it and write the general info
       if( ! ( outFile.equals("") ) )
       {
          try {
              outputFile = new FileOutputStream( outFile, true );
              outputStream = new PrintWriter( outputFile, true );
              writeHeader();
          } catch ( FileNotFoundException err ) {}
       }

//Data to for determining the position of items in the test
       if( size.equals( "1024x768" ) )
       {
             setBounds(0,0,1024,768);
             theX = ( 1024 / 2 ) - 200 / 2;
             theY = ( 768 / 2 )  - 200 / 2;
             w = 1024;
             h = 768;
             width = 200;
             height = 200;
             customSize = 200;
       }
       else
       {
             setBounds(0,0,800,600);
             theX = ( 800 / 2 ) - 150 / 2;
             theY = ( 600 / 2 )  - 150 / 2;
             w = 800;
             h = 600;
             width = 150;
             height = 150;
             customSize = 150;
       }
      //Handler for quitting the program when q/Q is pressed
       BypassHandler BP = new BypassHandler( this, t );
       this.addKeyListener( BP );

      //Handler for displaying the start image
       sh = new startHandler( this, theX, theY, width, height);
       this.addMouseListener( sh );

      //Make the visible visible and get mouse/keyboard focus
       this.setVisible(true);
       System.out.println("Focusable = " + this.isFocusable());
       this.setFocusable(true);
       buf = new BufferedImage(w , h, BufferedImage.TYPE_INT_RGB);
       g2 = buf.createGraphics();
       this.requestFocus();
       this.paintBuf( g2 );
   }

   //Function called by start handler when image is pressed
   protected void setup()
   {
      //Remove the start handler (no longer needed)
       removeMouseListener(sh);
       isSettingUp = true;

       //Program hasn't started, but init screen is not running
       started = 0;

      //Depending on which number program was selected, setup the appropriate variables
      // and call the constructor for the program
      // add the newly constructed program as a handlder to the window
      // schedule the timeAllowance timer (if program doesnt start w/ flashing)

       switch ( number )
       {

       //Shaping - Centered
        case 1:
          ii1 = ( ImageIcon ) theImages.elementAt( 0 );
          p1a =  new program1aHandler( this, theImages, theX, theY, delay,
             time, t , trials, delays, outputStream, w, h,  width, height, theC,
             countValid, correctSound, incorrectSound, reward, comPort, iti );

          addMouseListener( p1a );
          t.schedule( new Time ( p1a ), time * 1000 );
          break;

        // Shaping - Random location
        case 2:
          ii1 = ( ImageIcon ) theImages.elementAt( 0 );

          p1b =  new program1bHandler( this, theImages, theX, theY, delay,
             time, t ,  trials, delays, outputStream, w, h,  width, height, theC,
             countValid, correctSound, incorrectSound, reward, comPort, iti );

          addMouseListener( p1b );
          t.schedule( new Time ( p1b ), time * 1000 );
          break;

        //  Matching to sample - DMS
        case 3:
          theX2 = 0;
          theY2 = 0;
          p2a =  new program2aHandler( this, theImages, theX, theY, theX2, theY2, delay,
             time, t , trials, delays, outputStream, w, h, width, height, theC,
             countValid, correctSound, incorrectSound, reward, comPort, iti, isProgressiveDelays, correction );

          addMouseListener( p2a );
          t.schedule( new Time ( p2a ), time * 1000 );
          break;

        //Matching to sample - DNMS
        case 4:
          theX2 = 0;
          theY2 = 0;

          p2b =  new program2bHandler( this, theImages, theX, theY, theX2, theY2, delay,
             time, t , trials, delays, outputStream, w, h, width, height, theC,
             countValid, correctSound, incorrectSound, reward, comPort, iti, isProgressiveDelays, correction );

          addMouseListener( p2b );
          t.schedule( new Time ( p2b ), time * 1000 );
          break;

        // 5-> Spacial DRST 6-> Object DRST
        // These two programs are so similar and require a large amount of data
        // so they are put togeather

        case 5:
        case 6:
        {
          Random r = new Random();
          Vector positionX = new Vector(15);
          Vector positionY = new Vector(15);
          int xHelp, yHelp, theSize, whichOne, value, value2, ii;
          theXs = new int[15];
          theYs = new int[15];
          count = 1;
          baseline = 0;
          imageNames = new String[15];

          //Reset window data (images need to be smaller than standard to fit them all)
          if( size.equals("1024x768") )
          {
                width = 180;
                height = 180;
          }
          else
          {
                width = 125;
                height = 125;
          }

          // Position of the first image
          xHelp = 10;
          yHelp = ( h - (height * 3 ) ) / 4;

          // Create two vectors, one for the x coordinate valuse
          // one for the y values
          for( ii = 1; ii < 16; ii++ )
          {
              positionX.addElement( new Integer ( xHelp ) );
              positionY.addElement( new Integer ( yHelp ) );
              xHelp = xHelp + width + 10;
              // If this was the last image in the row, reset
              if ( ( ii % 5 ) == 0 )
              {
                  xHelp = 10;
                  yHelp = yHelp + height + ( h - (height * 3) ) / 4;
               }
          }

          //Pull the positions out of the vectors (in random order) and put them
          // into arrays (creates a set of positons in random order)
          for( ii = 0; ii < 15 ; ii++)
          {
             theSize = positionX.size() - 1;

             if( theSize > 1 )
             {
                  whichOne = r.nextInt( theSize );
                  value = ( ( Integer ) positionX.elementAt( whichOne ) ).intValue() ;
                  value2 = ( ( Integer ) positionY.elementAt( whichOne ) ).intValue() ;
             }
             else
             {
                  whichOne = 0;
                  value = ( ( Integer ) positionX.elementAt( whichOne ) ).intValue() ;
                  value2 = ( ( Integer ) positionY.elementAt( whichOne ) ).intValue() ;
             }
             positionX.removeElementAt( whichOne );
             positionY.removeElementAt( whichOne );
             theXs[ii] = value;
             theYs[ii] = value2;
         }

         // If the data point is in the middle row (of three) offset the X value
         // So the images arent in straight columns

         for( ii = 0; ii < 15; ii++)
         {
            if( theYs[ii] ==  ( ( h - (height * 3) ) / 4 ) + height + ( h - (height * 3) ) / 4 )
               theXs[ii] = theXs[ii] + ( ( h - (height * 3) ) / 4 );
         }

          if( number == 5 )
          {
              p3a =  new program3aHandler( this, theImages, theXs, theYs, delay,
                 time, t ,  trials, delays, outputStream, w, h, width, height, theC,
                 countValid, correctSound, incorrectSound, reward, comPort, iti  );

              addMouseListener( p3a );
              t.schedule( new Time ( p3a ), time * 1000 );
          }

          else
          {
              count = 0;
              p3b =  new program3bHandler( this, theImages, theXs, theYs, delay,
                 time, t ,  trials, delays, outputStream, w, h, width, height, theC,
                 countValid, baseline, correctSound, incorrectSound, reward, comPort, iti  );

              addMouseListener( p3b );
              t.schedule( new Time ( p3b ), time * 1000 );
          }
       }
       break;

       // Progressive Ratio
       case 7:
           p4 =  new program4Handler( this, theX, theY, delay,
              time, t , trials, delays, outputStream, w, h,  width, height,
              theC, countValid, pr, correctSound, incorrectSound, reward, comPort, iti  );

           addMouseListener( p4 );
           t.schedule( new Time ( p4 ), time * 1000 );
          break;

       // Delayed response
       case 8:
       //Positions are not standard so reset
          if( size.equals("1024x768") )
          {
                theX = 50;
                theY = h /2 - height / 2 + height / 4;
                theX2 = w - width - 50;
                theY2 = h /2 - height / 2 + height / 4;
          }
          else
          {
                theX = 50;
                theY = h /2 - height / 2 + height / 4;
                theX2 = w - width - 50;
                theY2 = h /2 - height / 2 + height / 4;
          }

          p5 =  new program5Handler( this, theX, theY, theX2, theY2, delay,
             time, t , trials, delays, outputStream, w, h, width, height, theC,
             countValid, correctSound, incorrectSound, reward, comPort, iti, isProgressiveDelays, correction  );

          addMouseListener( p5 );
         // Don't schedule timer.  Timer shouldn't start until flashing has finished
          break;

     //  Attention tasks
     case 9:
       {
          int xHelp, yHelp, theSize, whichOne, value, value2, ii;
          theXs = new int[12];
          theYs = new int[12];
          Random r = new Random();
          count = r.nextInt( 12 );

          //Positions are non standard so reset
          if( size.equals("1024x768") )
          {
                width = 130;
                height = 130;
          }
          else
          {
                width = 85;
                height = 85;
          }

          xHelp = width - width / 4;
          yHelp = (height / 4 );

          //Setup an array of positions
          for( ii = 1; ii < 13; ii++ )
          {
              theXs[ ii - 1 ] = xHelp;
              theYs[ ii - 1 ] = yHelp;
              xHelp = xHelp + w / 3 ;
              if ( ( ii % 3 ) == 0 )
              {
                  xHelp = width - width / 4;
                  yHelp = yHelp + h / 4;
              }
          }

         p6 =  new program6Handler( this, theXs, theYs, delay,
            time, t , trials, delays, outputStream, w, h, width, height, theC,
            countValid, attention, r, count, correctSound, incorrectSound, reward, comPort, iti  );

         addMouseListener( p6 );
         //Schedule time unless this is cued seach b/c cued search flashes
         if( attention != 3 ) t.schedule( new Time ( p6 ), time * 1000 );
       }
       break;

     // Conceptual set shifting
     case 10:
     {
       int isline;
       Random r = new Random();

       int xHelp, yHelp, theSize, whichOne, value, value2, ii, yStart;
       theXs = new int[9];
       theYs = new int[9];
       csstData = new int[9];

       xHelp = (w - width * 3 ) / 4;
       yHelp = (height / 6);
       yStart = yHelp;

       //Create array of positions
       for( ii = 1; ii < 10; ii++ )
       {
         theXs[ ii - 1 ] = xHelp;
         theYs[ ii - 1 ] = yHelp;


         xHelp = xHelp + (w - width * 3) / 4 + width;
         if ( ( ii % 3 ) == 0 )
         {
           xHelp =  (w - width * 3) / 4;
           yHelp = yHelp + h / 3;
         }
       }

       //this covers one row option
       if ( (card == 2) || (card == 3) )
       {
         isline = 3;
         yStart = yStart;
         for ( ii = 0; ii < 9; ii++ ) {
           theYs[ii] = yStart + h / 3;
         }
       }
       else {
         isline = 9;
       }



       p7 =  new program7Handler( this, theXs, theYs, delay,
                                  time, t , trials, delays, outputStream, w, h, width, height, theC,
                                  countValid, csst, r, csstData, correctSound, incorrectSound, reward, comPort, isline, iti );

       addMouseListener( p7 );
       t.schedule( new Time ( p7 ), time * 1000 );
     }
     break;


     //Custom CSST
   case 11:
   {

     int xHelp, yHelp, ii, buffer, Xedging, Yedging;
     customGrid = new int[9][3];

     Yedging = (  h - ( customSize * 3 ) ) / 8;
     buffer = ( h - ( customSize * 3 ) - ( Yedging * 2 ) ) / 2 ; //distance between cells
     Xedging = ( w - ( customSize * 3 ) - ( buffer * 2 ) ) / 2; //on sides


     xHelp = Xedging;
     yHelp = Yedging;

     //Create array of positions
     for( ii = 1; ii < 10; ii++ )
     {
       customGrid[ ii - 1 ][0] = -1;
       customGrid[ ii - 1 ][1] = xHelp;
       customGrid[ ii - 1 ][2] = yHelp;

       yHelp = yHelp + customSize + buffer;

       if ( ( ii % 3 ) == 0 )
       {
         xHelp =  xHelp + customSize + buffer;
         yHelp = Yedging;
       }
     }

     p8 = new program8Handler( this, delay, time, t, trials, delays, outputStream, theC,
                               countValid, correctSound, incorrectSound, reward, comPort,
                               iti, customTargets, customNumberStimuli, customSize, customShift );

     addMouseListener( p8 );
     t.schedule( new Time ( p8 ), time * 1000 );
   }
   break;

       // This should never happen, buf if it does just end (go back)
       default:
          end( 0 );
    }

    //Mark programs as having started
    started = 1;


    //If the program flashes, start the flashing
    if( number == 8 ) p5.flash();
    if(( number == 9 ) && (attention == 3)) p6.flash();

    //Create a new paint thread to make sure the screen has refreshed from the init screen
    paintThread pt = new paintThread( this );
    pt.start();

  }


  //When window is repainted draw the offscreen buffer to the window
    public void paint( Graphics screen ) {

        if(buf != null)
        {
           screen.drawImage( buf, 0, 0, null );
        }

    }

    //This is for when an image updates (such as a moving GIF)
    public void update(Graphics g) {
   //  DO NOTHING.  This is because animated GIFS update too fast and generate all sorts of crazy stuff.  This freezes them.
    }

    //This takes care of doing the actual drawing
    public synchronized void paintBuf ( Graphics g ) {

      //If the program hasn't started, draw the initial image
      if( started == -1)
      {

         g.drawImage( asterix.getImage() , theX, theY,  width, height, this );
         return;
      }

      //If the program is out of the initial handler, but new programs hasnt finished
      // Initializing, just draw a black screen

      else if( started == 0 )
      {
           g.setColor( colors[ 0 ] );
           g.fillRect(0, 0, w, h);
           return;
      }

      // If the program has started, draw the appropriate images depending on data
      // Manipulated by program handler
      switch( number )
      {

        // For Shaping programs, if count is positive draw the image at specified position
        // Otherwise fill screen with selected color
        case 1:
        case 2:
          if ( count >= 0 )
          {
             g.setColor( colors[ 0 ] );
             g.fillRect(0, 0, w, h);

             ii1 = (ImageIcon) theImages.elementAt(count);
             g.drawImage( ii1.getImage() , theX, theY,  width, height, this );

          }
          else
          {
               g.setColor( colors[ (count * -1) - 1 ] );
               g.fillRect(0, 0, w, h);
          }

          break;

        // For DMS and DMNS if count >= 0 draw images
        // Otherwise colored screen
        case 3:
        case 4:
          if( ( count >= 0 ) )
          {
            g.setColor( colors[ 0 ] );
            g.fillRect(0, 0, w, h);
            if ( ( swap == 1) || ( numberOfImages == 1 ) )
            {
               ii1 = ( ImageIcon ) theImages.elementAt( count );
               ii2 = ( ImageIcon ) theImages.elementAt( count + 1 );
            }
            else
            {
               ii1 = ( ImageIcon ) theImages.elementAt( count + 1 );
               ii2 = ( ImageIcon ) theImages.elementAt( count );
            }

            g.drawImage( ii1.getImage() , theX, theY, width, height, this );
          }
         else
          {
            ii2 = null;
            g.setColor( colors[ (count * -1) - 1 ] );
            g.fillRect(0, 0, w, h);
          }


         // If this is a screen w/ 2 images, draw second image
         if( ( ii2 != null ) && ( numberOfImages == 2 ) )
         {
             g.drawImage( ii2.getImage() , theX2, theY2, width, height, this );
         }

         break;

       // if count > 0 draw all images needed, otherwise colored screen
       case 5:
             if( count > 0 )
             {
                g.setColor( colors[ 0 ] );
                g.fillRect(0, 0, w, h);
                ii1 = ( ImageIcon ) theImages.elementAt( 0 );
                for (int ii = count - 1; ii >= 0 ; ii--)
                {
                      g.drawImage( ii1.getImage() , theXs[ii] , theYs[ii], width, height, this );
                }
             }

             else
             {
               g.setColor( colors[ (count * -1) - 1 ] );
               g.fillRect(0, 0, w, h);
             }
       break;

       // if count > 0 draw all images needed, otherwise colored screen
       case 6:
             if( count >= 0 )
             {
                int temp;
                int temp2;
                g.setColor( colors[ 0 ] );
                g.fillRect(0, 0, w, h);
                for (int ii = count; ii >= 0 + baseline ; ii--)
                {
                      if ( ii >= theImages.size() )
                         temp = ii % theImages.size();
                      else
                         temp = ii;

                      ii1 = ( ImageIcon ) theImages.elementAt( temp  );
                      g.drawImage( ii1.getImage() , theXs[ii % theXs.length ] , theYs[ii % theYs.length ], width, height, this );
                      String tempStr = new String(ii1.toString());
                      int temp3 = tempStr.lastIndexOf("\\");  //this section gets the filename
                      tempStr = tempStr.substring( temp3+1 , tempStr.length() );
                      imageNames[ii % theXs.length] = tempStr;
                }

             }
             else
             {
               g.setColor( colors[ (count * -1) - 1 ] );
               g.fillRect(0, 0, w, h);
             }
       break;

       // if count >= 0 draw centered square, otherwise colored screen
       case 7:
          if ( count >= 0 )
          {
            g.setColor( colors[ 0 ] );
            g.fillRect(0, 0, w, h);
            g.setColor( colors[ 6 ] );
            g.fillRect(theX, theY, width, height );
          }
          else
          {
               g.setColor( colors[ (count * -1) - 1 ] );
               g.fillRect(0, 0, w, h);
          }

       break;

       //If count is 100 draw the two squares
       // If < 0 draw colored screen
       // If equal to 0 draw the circle (cue during flash) by left sqauare
       // If equal to 1 draw the circle (cue during flash) by right sqaure
       case 8:
          if(count >= 0 )
          {
            g.setColor( colors[ 0 ] );
            g.fillRect(0, 0, w, h);
          }

          if( ( count == 100 ) )
          {
            g.setColor(colors[ 6 ]);
            g.fillRect(50, h /2 - height / 2, width, height);
            g.fillRect(w - width - 50, h /2 - height / 2, width, height);
          }
          else if ( count < 0 )
          {
            g.setColor( colors[ (count * -1) - 1 ] );
            g.fillRect(0, 0, w, h);
          }
          else if ( count == 0 )
          {
            g.setColor(colors[ 7 ]);
            g.fillArc(width / 2 + width / 4, h /2 - height / 2 + height / 4, width / 4, height / 4, 0 , 360);
          }
          else if ( count == 1 )
          {
            g.setColor(colors[ 7 ]);
            g.fillArc(w - width / 2 - 50 - width / 4, h /2 - height / 2 + height / 4, width / 4, height / 4, 0 , 360);
          }

         break;
     //If count is between 0 and 100 draw all the circles
     // If < 0 draw colored screen
     // If > 100 draw circle in specified position only (used for flashing)
     case 9:
        if (( count >= 0 ) && (count < 100))
        {
           g.setColor( colors[ 0 ] );
           g.fillRect(0, 0, w, h);

           //this controls the color of the circles before the star
           if ( attention == 1 ) g.setColor(colors[ 6 ]);
           else g.setColor(colors[ 7 ]);

           for( int ii = 0; ii < 12; ii++ )
            if(( ii != count) && (attention != 0))
               g.fillArc(theXs[ii], theYs[ii], width,  height, 0 , 360);
            else if ( ii == count)
            {
               //The Star
               int[] xPoints = { theXs[ii], theXs[ii] + width / 3,
                   theXs[ii] + width / 2,
                   theXs[ii] + 2 * (width / 3),
                   theXs[ii] + width,
                   theXs[ii] + 3 * (width / 4),
                   theXs[ii] + 7 * (width / 8),
                   theXs[ii] + width / 2,
                   theXs[ii] + (width / 8),
                   theXs[ii] + ( width / 4) };

               int[] yPoints = { theYs[ii] + height / 3, theYs[ii] + height / 3, theYs[ii], theYs[ii] + height / 3,
                  theYs[ii] + height / 3, theYs[ii] + 3 * ( height / 5), theYs[ii] + height, theYs[ii] + 3 * (height / 4), theYs[ii] + height,
                  theYs[ii] + 3 * (height / 5) };
               g.setColor(colors[ 7 ]);  //the star
               g.fillPolygon( xPoints, yPoints, xPoints.length);

               //this controls the color of the circles after the star
               if ( attention == 1 ) g.setColor(colors[ 6 ]);
               else g.setColor(colors[ 7 ]);
            }
        }
        else if ( count >= 100 )
        {
            g.setColor( colors[ 0 ] );
            g.fillRect(0, 0, w, h);
            g.setColor(colors[ 6 ]); //cue is yellow
            g.fillArc(theXs[count - 100], theYs[count - 100], width , height, 0 , 360);

        }
        else
        {
            g.setColor( colors[ (count * -1) - 1 ] );
            g.fillRect(0, 0, w, h);
        }
        break;

     // If csstData[0] is greater than 0
     // And csst equals 0 (discrimination) draw the three shapes
     // Otherwise draw level X shapes
     // If csstData[0] is less than 0 draw colored screen
     case 10:
       if ( (card == 0) || (card == 2) ) //no cards
       {
         if ( csstData[0] >= 0 )
         {
           g.setColor( colors[ 0 ] );
           g.fillRect(0, 0, w, h);

           if( csst == 0)
           {
              for( int ii = 0; ii < 3; ii++ )
              {
                 g.setColor(colors[ 0 ]);
                 g.fillRect(theXs[csstData[ii]], theYs[csstData[ii]], width,  height);

                 if( csstData[ ii + 3 ] == 0 )
                 {
                     g.setColor(colors[10] );
                     g.fillRect( theXs[csstData[ii]], theYs[csstData[ii]], width,  height);
                 }

                 else if( csstData[ ii + 3 ] == 1 )
                 {
                     g.setColor(colors[11] );
                     g.fillRect( theXs[csstData[ii]], theYs[csstData[ii]] + height / 2 - height / 16, width,  height / 8);
                     g.fillRect( theXs[csstData[ii]] + width / 2 - width / 16, theYs[csstData[ii]], width / 8,  height);
                 }

                 else
                 {
                     g.setColor( colors[6] );
                     int[] xPoints = { theXs[csstData[ii]],
                         theXs[csstData[ii]] + width / 2,
                         theXs[csstData[ii]] + width,
                         theXs[csstData[ii]] + width,
                         theXs[csstData[ii]] + width / 2,
                         theXs[csstData[ii]]};


                     int[] yPoints = { theYs[csstData[ii]],
                        theYs[csstData[ii]] + height / 2,
                        theYs[csstData[ii]],
                        theYs[csstData[ii]] + height,
                        theYs[csstData[ii]] + height / 2,
                        theYs[csstData[ii]] + height};

                     g.fillPolygon( xPoints, yPoints, xPoints.length);
                 }
              }
           }
           else
           {
              for( int ii = 0; ii < 3; ii++ )
              {
                 g.setColor(colors[ 0 ]);
                 g.fillRect(theXs[csstData[ii]], theYs[csstData[ii]], width,  height);

                 if ( csstData[ii+6] == 0) g.setColor(colors[7]);
                 else if ( csstData[ii+6] == 1) g.setColor(colors[3]);
                 else if ( csstData[ii+6] == 2) g.setColor(colors[1]);

                 if( csstData[ ii + 3 ] == 0 )
                     g.fillArc( theXs[csstData[ii]], theYs[csstData[ii]], width,  height, 0, 360);

                 else if( csstData[ii + 3 ] == 1 )
                 {
                    int[] xPoints = { theXs[csstData[ii]], theXs[csstData[ii]] + width / 2 ,
                       theXs[csstData[ii]] + width};

                    int[] yPoints = { theYs[csstData[ii]] + height, theYs[csstData[ii]],
                       theYs[csstData[ii]] + height};

                    g.fillPolygon( xPoints, yPoints, xPoints.length);
                 }

                 else
                 {
                     int[] xPoints = { theXs[csstData[ii]],
                        theXs[csstData[ii]] + 2 * (width / 6 ),
                        theXs[csstData[ii]] + 3 * (width / 6 ),
                        theXs[csstData[ii]] + 4 * (width / 6 ),
                        theXs[csstData[ii]] + width,
                        theXs[csstData[ii]] + 4 * (width / 6 ),
                        theXs[csstData[ii]] + 5 * (width / 6 ),
                        theXs[csstData[ii]] + 3 * (width / 6 ),
                        theXs[csstData[ii]] + 1 * (width / 6 ),
                        theXs[csstData[ii]] + 2 * (width / 6 ) };

                     int[] yPoints = { theYs[csstData[ii]] + 4 * (height / 12),
                        theYs[csstData[ii]] + 4 * (height / 12),
                        theYs[csstData[ii]],
                        theYs[csstData[ii]] + 4 * (height / 12),
                        theYs[csstData[ii]] + 4 * (height / 12),
                        theYs[csstData[ii]] + 7 * (height / 12),
                        theYs[csstData[ii]] + height,
                        theYs[csstData[ii]] + 9 * (height / 12),
                        theYs[csstData[ii]] + height,
                        theYs[csstData[ii]] + 7 * (height / 12) };

                     g.fillPolygon( xPoints, yPoints, xPoints.length);
                 }
              }
           }
        }
        else
        {
            g.setColor( colors[ (csstData[0] * -1) - 1 ] );
            g.fillRect(0, 0, w, h);
        }
       }//end if card == 0 or 2
       else if ( (card == 1) || (card == 3) || (card == 4 ) ) //they want the cards
       {

         if ( card == 4)  //we're using the alternate colors
         {
           colors[13] = colors[11];
           colors[14] = colors[6];
         }

         if ( csstData[0] >= 0 )
         {
           g.setColor( colors[ 0 ] );
           g.fillRect(0, 0, w, h);

           if( csst == 0)
           {
             for( int ii = 0; ii < 3; ii++ )
             {
               g.setColor(colors[ 8 ]);
               g.fillRect(theXs[csstData[ii]], theYs[csstData[ii]], width,  height);

               if( csstData[ ii + 3 ] == 0 )
               {
                 g.setColor(colors[5] );
                 g.fillRect( theXs[csstData[ii]] + width / 4, theYs[csstData[ii]] + height / 4, width / 2,  height / 2);
               }

               else if( csstData[ ii + 3 ] == 1 )
               {
                 g.setColor(colors[4] );
                 g.fillRect( theXs[csstData[ii]] + width / 4, theYs[csstData[ii]] + height / 2 - height / 16, width / 2,  height / 8);
                 g.fillRect( theXs[csstData[ii]] + width / 2 - width / 16, theYs[csstData[ii]] + height / 4, width / 8,  height / 2);
               }

               else
               {
                 g.setColor( colors[9] );
                 int[] xPoints = { theXs[csstData[ii]] + width / 4,
                   theXs[csstData[ii]] + width / 2,
                   theXs[csstData[ii]] + 3 * (width / 4),
                   theXs[csstData[ii]] + 3 * (width / 4),
                   theXs[csstData[ii]] + width / 2,
                   theXs[csstData[ii]] + width / 4 };


                 int[] yPoints = { theYs[csstData[ii]] + height / 4,
                   theYs[csstData[ii]] + height / 2,
                   theYs[csstData[ii]] + height / 4,
                   theYs[csstData[ii]] +  3 * ( height / 4),
                   theYs[csstData[ii]] + height / 2,
                   theYs[csstData[ii]] +  3 * ( height / 4)};

                 g.fillPolygon( xPoints, yPoints, xPoints.length);
               }
             }
           }
           else
           {
             for( int ii = 0; ii < 3; ii++ )
             {
               g.setColor(colors[ 8 ]);
               g.fillRect(theXs[csstData[ii]], theYs[csstData[ii]], width,  height);

               if ( csstData[ii+6] == 0) g.setColor(colors[13]);
               else if ( csstData[ii+6] == 1) g.setColor(colors[14]);
               else if ( csstData[ii+6] == 2) g.setColor(colors[1]);

               if( csstData[ ii + 3 ] == 0 )
                 g.fillArc( theXs[csstData[ii]] + width / 4, theYs[csstData[ii]] + height / 4, width / 2,  height / 2, 0, 360);

               else if( csstData[ii + 3 ] == 1 )
               {
                 int[] xPoints = { theXs[csstData[ii]] + width / 4, theXs[csstData[ii]] + width / 2 ,
                   theXs[csstData[ii]] + width / 4 + width / 2};

                 int[] yPoints = { theYs[csstData[ii]] + height / 4 + height / 2, theYs[csstData[ii]] + height / 4,
                   theYs[csstData[ii]] + height / 4 + height / 2};

                 g.fillPolygon( xPoints, yPoints, xPoints.length);
               }

               else
               {
                 int[] xPoints = { theXs[csstData[ii]] + width / 4,
                   theXs[csstData[ii]] + width / 3 + width / 4,
                   theXs[csstData[ii]] + width / 2 ,
                   theXs[csstData[ii]] + 2 * (width / 3) - width / 4,
                   theXs[csstData[ii]] + width - width / 4,
                   theXs[csstData[ii]] + 3 * (width / 4) - width / 8,
                   theXs[csstData[ii]] + 7 * (width / 8) - width / 6,
                   theXs[csstData[ii]] + width / 2,
                   theXs[csstData[ii]] + (width / 8) + width / 6,
                   theXs[csstData[ii]] + ( width / 4) + width / 8 };

                 int[] yPoints = { theYs[csstData[ii]] + height / 4 + height / 6,
                   theYs[csstData[ii]] + height / 4 + height / 6,
                   theYs[csstData[ii]] + height / 4,
                   theYs[csstData[ii]] + height / 4 + height / 6,
                   theYs[csstData[ii]] + height / 4 + height / 6,
                   theYs[csstData[ii]] + ( height / 2) + height / 20,
                   theYs[csstData[ii]] + height - height / 8 - height / 8,
                   theYs[csstData[ii]] + 3 * (height / 4) - height / 8,
                   theYs[csstData[ii]] + height - height / 8 - height / 8,
                   theYs[csstData[ii]] + (height / 2) + height / 20};

                 g.fillPolygon( xPoints, yPoints, xPoints.length);
               }
             }
           }
         }
         else
         {
           g.setColor( colors[ (csstData[0] * -1) - 1 ] );
           g.fillRect(0, 0, w, h);
         }

       }//end else for cards
       break;


       //custom CSST
       case 11:
         if (skipInitial == 0) {
           skipInitial = 1;
           return;
         } //we do this because our handler draws the first screen


         if ( isBetween == 3 ) {
           g.setColor( colors[ 7 ] );
           g.fillRect(0, 0, w, h);
         }

         else if ( isBetween == 2 ) {
           g.setColor( colors[ theC ] );
           g.fillRect(0, 0, w, h);
         }

         else {
           g.setColor( colors[ 0 ] );
           g.fillRect(0, 0, w, h); //paints the black background

           if ( isBetween == 0 ) {
             //now draw the images
             for ( int i = 0 ; i < 9 ; i++ ) {
               if ( customGrid[i][0] != -1 ) {
                 g.drawImage( (Image)customImages[customGrid[i][0]][1] , customGrid[i][1], customGrid[i][2],  customSize, customSize, this );
               }//end if
             } //end for
           } //end if
         } //end else

         break;

      }
      readytobypass = 1;
    } //end paintBuf

  //Used for program Handlers to change "count"
   protected int changeCount( int c ) {
   int old;
      old = count;
      count = c;
      return old;
   }

   // Used for program Handlers to change "baseline" (used for DRST tasks)
   protected void changeBaseline( int c ) { baseline = c; }

   // Used for program Handlers to change x and y positions
   protected void loc(int x, int y, int x2, int y2, int s, int nI )
   {
      theX = x;
      theY = y;
      theX2 = x2;
      theY2 = y2;
      swap = s;
      numberOfImages = nI;
   }

   // When the program is supposed to stop
   // Call the quit function of the running program (if one has started)
   protected void end( int kill )
   {
     System.out.println("ending");
     if( started > 0 )
     {
       switch( number )
       {
         case 1:
           p1a.quit();
           break;
         case 2:
           p1b.quit();
           break;
         case 3:
           p2a.quit();
           break;
         case 4:
           p2b.quit();
           break;
         case 5:
           p3a.quit();
           break;
         case 6:
           p3b.quit();
           break;
         case 7:
           p4.quit();
           break;
         case 8:
           p5.quit();
           break;
         case 9:
           p6.quit();
           break;
         case 10:
           p7.quit();
           break;
         case 11:
           p8.quit();
           break;
       }
     }

     // Close the sounds
     if( correctSound != null) correctSound.close();
     if( incorrectSound != null) incorrectSound.close();

     // If this was a Q then quit entire program
     if ( kill == 1 )
       System.exit(1);

     // Otherwise hide this base and show program selector
     else
     {
        tWindow.setVisible( true );
        this.setVisible(false);
     }
   }

   protected void updateGraphics()
   {
    paintThread pt = new paintThread( this );
    pt.start();
   }

// When the programs is supposed to stop
   // Call the quit function of the running program (if one has started)
   protected void bypass(KeyEvent k)
   {
     buttonPress = k;
     if( (started > 0) && (readytobypass == 1 ) )
     {
        switch( number )
        {
          case 1:
            p1a.bypass();
            break;
          case 2:
            p1b.bypass();
            break;
          case 3:
            p2a.bypass();
            break;
          case 4:
            p2b.bypass();
            break;
          case 5:
            p3a.bypass();
            break;
          case 6:
            p3b.bypass();
            break;
          case 7:
            p4.bypass();
            break;
          case 8:
            p5.bypass();
            break;
          case 9:
            p6.bypass();
            break;
          case 10:
            p7.bypass();
            break;
          case 11:
            p8.bypass();
            break;
        }
     }
   }




   // This function writes the header in formation for a program
   private void writeHeader( )
   {

       outputStream.println( "Date:              " + Date );
       outputStream.println( "Monkey ID:         " + Id );
       outputStream.println( "Task:              " + prog );
       if( (number == 3) || (number == 4) || (number == 8) ){
         if (correction == 0)
           outputStream.println("Forced correction procedure");
         else if (correction == 1)
           outputStream.println("No correction procedure");
         else if (correction == 2)
           outputStream.println("Correction procedure on");
       }
       else if (number == 10 )
       {
          if( csst == 0 ) outputStream.println(" (Discrimination)");
          if( csst == 1 ) outputStream.println(" (Level 1)");
          if( csst == 2 ) outputStream.println(" (Level 2)");
          if( csst == 3 ) outputStream.println(" (Level 3)");
          if( csst == 4 ) outputStream.println(" (Level 4)");
       }
       else if (number == 9)
       {
          if( attention == 0 ) outputStream.println(" (Training)");
          else if( attention == 1 ) outputStream.println(" (Simple Search Easy)");
          else if( attention == 2 ) outputStream.println(" (Simple Search Hard)");
          else if( attention == 3 ) outputStream.println(" (Cued Search)");
       }
       else if (number == 7 )
       {
          if( pr == 0 ) outputStream.println(" (Fixed Ratio 1)");
          else if( pr == 1 ) outputStream.println(" (Fixed Ratio 2)");
          else if( pr == 2 ) outputStream.println(" (Fixed Ratio 3)");
          else if( pr == 3 ) outputStream.println(" (Fixed Ratio 4)");
          else if( pr == 4 ) outputStream.println(" (Fixed Ratio 5)");
          else if( pr == 5 ) outputStream.println(" (Fixed Ratio 6)");
          else if( pr == 6 ) outputStream.println(" (Progressive Ratio)");
       }

       outputStream.println( "Tested By:         " + Tester );
       outputStream.println( "Image Directory:   " + imageDirectory );
       outputStream.println( "ITI:               " + iti );
       outputStream.print(   "Database Host:     ");

       if (dbHost.equals("")) {
         outputStream.println("NONE");
       }
       else {
         outputStream.println(dbHost);
       }


       outputStream.println( " " );
       outputStream.println( "Trial" );
   }



}
package yerkes;

import java.awt.event.*;
import java.util.*;

/**
 * Title:
 * Description:
 * Copyright:    Copyright (c) 2005
 * Company:
 * @author  Zachary William Anderson
 * @version 1.0
 */

//Used while program is running to end it
public class BypassHandler implements KeyListener {
  private Base theBase;
  private java.util.Timer time;

  public BypassHandler(Base b, java.util.Timer t) {
    System.out.println("Bypass constructed");
    theBase = b;
    time = t;
  }

  public void keyPressed(KeyEvent k) {}

  public void keyTyped(KeyEvent k) {
    System.out.println("The key is " + k.getKeyChar());
    if (k.getKeyChar() == 'q') {
      time.cancel();
      theBase.end(0);
    }

    else if (k.getKeyChar() == 'Q') {
      time.cancel();
      theBase.end(1);
    }
    else if (k.getKeyChar() == ' ') {
      if (theBase.readytobypass == 1) {

        theBase.bypass(k);
      }
      //this is for bypassing the openning image
      else if (!theBase.isSettingUp) {
        theBase.started = 0;
        theBase.updateGraphics();
        try {
          Thread.sleep(750);
        }
        catch (Exception ex) {}
        theBase.setup();
      }
    }


}

  //When a key is pressed do associated action
  public void keyReleased(KeyEvent k) {
}
}
/*handles the shaping - centered task*/

package yerkes;

import java.awt.event.*;
import java.util.*;
import java.io.*;
import java.text.*;
import javax.sound.sampled.*;


public class program1aHandler extends programGenericHandler {
  private int count, number, trials, color, running, countValid, numrefused;
  private int X, Y, Width, Height, wWidth, wHeight, reward, comPort;
  private Base theBase;
  private int delay, time;
  private java.util.Timer t2;
  private float[] delays;
  private float meanResponseTime, correct;
  private PrintWriter out;
  private long timeStart, timeEnd;
  private DecimalFormat f = new DecimalFormat( "0.000" );
  private DecimalFormat f2 = new DecimalFormat( "0.00" );
  private DecimalFormat f3 = new DecimalFormat( "0" );
  private paintThread pt;
  private static long lastTime, offsetTime;
  private Clip correctSound, incorrectSound;
  private com runOutput;

  //this is all db stuff
  private databaseHandler dbase = new databaseHandler();
  private String sessionid, trialline, summaryline, datetime, tester, completed, imageDirectory;
  private String result, monkeyid, dbMeanResponseTime, dbCorrect, dbWrong, dbPercentCorrect;
  private String DV, finial, stakes, trialstakes, dbTime;
  private String[] sessiondate;
  private int trialNumber;
  private float iti;


  public program1aHandler( Base b, Vector Images, int x, int y, int d, int t,
    java.util.Timer timer, int tr, float[] de, PrintWriter pOut, int w, int h,
    int iW, int iH, int c, int v, Clip CS, Clip IS, int rgb, int cP, float ititemp ) {

    iti = ititemp;
    numrefused = 0;
    theBase = b;
    X = x;
    Y = y;
    delay = d;
    time = t ;
    t2 = timer;
    trials = tr;
    number = 0;
    delays = de;
    out = pOut;
    correct = 0;
    meanResponseTime = 0;
    Width = iW;
    Height = iH;
    color = c;
    running = 1;
    countValid = v;
    correctSound = CS;
    incorrectSound = IS;
    lastTime = System.currentTimeMillis();
    offsetTime = 0;
    reward = rgb;
    comPort = cP;

    //db variable initializers
    monkeyid = theBase.monkeyid;
    sessiondate = dbase.getSessionInfo(monkeyid);
    sessionid = sessiondate[0];
    datetime = sessiondate[1];
    tester = theBase.Tester;
    imageDirectory = theBase.imageDirectory;
    finial = "')"; //end of db strings
    DV = "', '"; //divider for db strings

    timeStart = System.currentTimeMillis();
  }

//Handles spacebar shortcut
  public void bypass() {
    if( theBase.buttonPress.getWhen() <= timeStart ) return;
    performactions( X, Y, 1, 1 );
  }




//When click occurs, do this
   public void mousePressed(MouseEvent e) {
     int x, y, good;

//If the click came before the last handler was finished (before image was shown)
// then ignore it
     if( e.getWhen() <= timeStart ) return;

//If Program is no longer running, ignore clicks
     if( running == 0 ) return;

     x = e.getX();
     y = e.getY();

/*
     Should this be a valid click?
     If non-image clicks are allowed, the click is valid
     If the click was at position -1 -1 (generated by timeout timer) it is valid
     If the click is inside the image it is valid
*/
     if ( (countValid == 0 ) || ( x == -1 ) ) good = 1;
     else good = check(x,y);

     performactions( x, y, good, 0 );
   }

//this performs the actions after a mouseclick or the bypass key
   public void performactions( int x, int y, int good, int assumegood ) {
     //If this is a valid click and the program is still running
     if ( ( running == 1 ) && ( good == 1 ) )
     {

     //Cancel the timeout timer, and record the end time

        t2.cancel();
        timeEnd = System.currentTimeMillis();

        if ( check( x, y ) == 1 ) clear_good();
        else clear_bad(x);

        //If we are still running, reschedule the timeout timer and start time
       if ( running == 1)
       {
         t2 = new java.util.Timer();
         t2.schedule( new Time( this ), time * 1000 );
       }
       timeStart = System.currentTimeMillis();
     }

  }

//Checks to see if click was correct
  int check(int x,int y) {
    if ( ( ( x >= X ) && ( x <= ( X + Width ) ) ) && ( ( y >= Y ) && ( y <= ( Y + Height ) ) )  )
      return 1;
    else return 0;
  }


  //Do this if a correct response was given
  private void clear_good( ){
  int old;

     playSound(correctSound);

     rewardGood( reward, comPort);

     old = theBase.changeCount( -1 );

     theBase.updateGraphics();

     if( out != null ) updateHeader( 0 );

     pause(iti);

     number++;

     //If all the trials have completed, show the red screen, print summary info, and stop
     if( number >= trials )
     {
          running = 0;
          old = theBase.changeCount( -8 );
          theBase.updateGraphics();
          if( out != null ) summary();
          return;
     }

     //If still running, move to next image and start again
     else {
        old = theBase.changeCount ( old + 1 );
        theBase.updateGraphics();
     }

  }

  private void clear_bad( int x ) {
  int old, old2;
     playSound(incorrectSound);
     rewardBad(reward, comPort);

     old = theBase.changeCount( ( color * -1) -1 );
     theBase.updateGraphics();

     if ((out != null) && ( x == -1))
     {
       updateHeader( 2 );
       numrefused++;
     }
     else if( out != null ) updateHeader( 1 );

     pause( delay );
     number++;

     //If all the trials have completed, show the red screen, print summary info, and stop
     if( number >= trials )
     {
         running = 0;
         old = theBase.changeCount( -8 );
         theBase.updateGraphics();
         if( out != null ) summary();
         return;
     }
     else {
        old2 = theBase.changeCount ( old + 1 );
        theBase.updateGraphics();
     }
   }

   private void updateHeader ( int status ) {

     double time;
     time = (timeEnd - timeStart ) / 1000.0;
     out.print( (number + 1) + " ");
     if ( status == 0 )
     {
       out.print( "Correct" + "\t " );
       result = "correct";
       correct++;
     }
     else if (status == 2) {
       out.print( "Refused  " + "\t " );
       result = "refused";
     }
     else {
       out.print( "Wrong  " + "\t " );
       result = "wrong";
     }

     out.println( f.format( time ) );

     if (status != 2) meanResponseTime += time;



     //Insert Trial into DB
     trialNumber = number + 1;
     dbTime = f.format( time );

     trialstakes = "insert into shaping_centered_trials (id, trialNumber, result, responseTime ) values ( '";

     trialline = trialstakes +
                   sessionid + DV + trialNumber + DV + result + DV + dbTime +
                   finial;

     if ( ! theBase.dbHost.equals("")) {
     try {
     dbase.DBupdate( theBase.dbHost, trialline); }
     catch ( java.lang.Exception e ) {
     System.out.println ( "Error executing sql statement" ); }
     }

   }

   public void summary( )
   {
      out.println("");
      out.println("Summary: ");
      out.println("");

      out.println("Number of Trials:   " + number );
      out.println("Number Refused:     " + numrefused );
      out.println("Number Correct:     " + f3.format(correct) );
      out.println("Number Wrong:       " + f3.format( (number - correct - numrefused) ) );
      if(( correct == 0 ) || (number == 0)) {
         out.println("Percent Correct:    " + "0.00" + "%");
         dbPercentCorrect = "0";
      }
      else {
         out.println("Percent Correct:    " + f2.format ( ( correct / ( number - numrefused ) ) * 100.0 ) +"%" );
         dbPercentCorrect = f2.format ( ( correct / ( number - numrefused ) ) * 100.0 );
      }
      if(number != 0 ) {
        out.println("Mean Response Time: " + f.format( meanResponseTime / ( number - numrefused ) ) );
        dbMeanResponseTime = f.format( meanResponseTime / ( number - numrefused ) );
      }
      else {
        out.println("Average Span: 0");
        dbMeanResponseTime = "";
      }
      out.println("Session ID: " + sessionid );
      out.println("------------------------------------------------------------------" );
      out.println(" ");
      out.close();


      //Insert Summary into DB
      dbCorrect = f3.format(correct);
      dbWrong = f3.format( (number - correct - numrefused) );
      completed = "yes";

      stakes =
          "insert into shaping_centered (id, date, monkey, tester, timeout, numberTrials, numberRefused, numberCorrect, numberWrong, percentCorrect, meanResponseTime, completed, imageDirectory, iti ) values ( '";

      summaryline = stakes +
                    sessionid +  DV + datetime + DV + monkeyid + DV + tester + DV + delay + DV +
                    number +  DV + numrefused +  DV + dbCorrect +  DV + dbWrong +  DV +
                    dbPercentCorrect + DV + dbMeanResponseTime + DV + completed + DV + imageDirectory + DV + iti +
                    finial;

     if ( ! theBase.dbHost.equals("")) {
     try {
     dbase.DBupdate( theBase.dbHost, summaryline); }
     catch ( java.lang.Exception e ) {
     System.out.println ( "Error executing sql statement" ); }
     }

   }

   //This is called if the program is terminated before it has finished
   public void summaryBad()
   {
      out.println("");
      out.println("Summary: ");
      out.println("");
      out.println("TEST ABORTED");
      out.println("Session ID: " + sessionid );
      out.println("------------------------------------------------------------------" );
      out.println(" ");
      out.close();


      //Insert Summary into DB
      if ( completed == "yes" )
        return;

      completed = "no";

      stakes =
          "insert into shaping_centered (id, date, monkey, tester, timeout, numberTrials,  completed, imageDirectory, iti ) values ( '";

      summaryline = stakes +
                    sessionid +  DV + datetime + DV + monkeyid + DV + tester + DV + delay + DV +
                    number + DV + completed + DV + imageDirectory + DV + iti +
                    finial;

      if ( ! theBase.dbHost.equals("")) {
        try {
        dbase.DBupdate( theBase.dbHost, summaryline); }
        catch ( java.lang.Exception e ) {
        System.out.println ( "Error executing sql statement" ); }
      }

   }
   public void quit(){ t2.cancel(); if(out != null) summaryBad(); }
}
package yerkes;
import java.awt.event.*;
import javax.sound.sampled.*;

/**
 * Title:        CRS
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:      Yerkes
 * @author Pearce Peck-Walden
 * @version 1.0
 */


//This class provides the methods that are common to all programHandlers

 abstract class programGenericHandler implements MouseListener{

  public programGenericHandler() {
  }

   public void mouseExited(MouseEvent e) { }
   public void mouseEntered(MouseEvent e) { }
   public void mouseReleased(MouseEvent e) { }
   public void mouseClicked(MouseEvent e) { }

   abstract public void mousePressed(MouseEvent e);

   abstract public void bypass();

   abstract public void performactions( int x, int y, int good, int assumegood );

   abstract int check(int x, int y);


   //Pause for a specified amount of time
   void pause(float time)
   {
      try {
       Thread.sleep( ( int ) ( time * 1000 ) );
      } catch (InterruptedException e ) {}

   }

   //Play a sound
   void playSound(Clip sound)
   {
        if(sound != null)
        {
           sound.start();
           sound.setFramePosition( 0 );
        }
   }

   //Ouput a good reward if the option was specified
   void rewardGood(int reward, int comPort)
   {
     if( (reward == 1) || (reward == 3))
     {
       if ( comPort == 6 )
       {
         //do usb stuff here
         usbHandler runOutput;
         runOutput =  new usbHandler();
         runOutput.start();
       }
       else
       {
         com runOutput;
         runOutput = new com(comPort, 0 );
         runOutput.start();
       }
     }
   }

   //Output a bad reward if the option was specified
   void rewardBad(int reward, int comPort)
   {

     if( (reward == 2) || (reward == 3))
     {
       if ( comPort == 6 )
       {
         //do usb stuff here
         usbHandler runOutput;
         runOutput =  new usbHandler();
         runOutput.usbRewardBad();
       }
       else
       {
         com runOutput;
         runOutput = new com(comPort, 1 );
         runOutput.start();
       }
     }
   }

   public void quit(){}
}
package yerkes;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;



//This creates GUI for running programs
class ProgramSelector extends JFrame implements ActionListener{


    // GUI components
    private JPanel panel1 = new JPanel();
    private JPanel panel2 = new JPanel();
    private JPanel panel3 = new JPanel();
    private JPanel panel4 = new JPanel();
    private JMenuBar jmb = new JMenuBar();
    private JMenu jmFile = new JMenu("File");
    private JMenu jmHelp = new JMenu("Help");
    private JMenu jmTools = new JMenu("Tools");
    private JMenuItem jmi1 = new JMenuItem("Save Settings");
    private JMenuItem jmi2 = new JMenuItem("Load Settings");
    private JMenuItem jmi3 = new JMenuItem("Start");
    private JMenuItem jmi4 = new JMenuItem("Exit");
    private JMenuItem jmi5 = new JMenuItem("About");
    private JMenuItem jmi6 = new JMenuItem("Image Converter");

    protected JTextField jtfDate = new JTextField( 10 );
    protected JTextField jtfOutputLoc = new JTextField( 3 );
    protected JTextField jtfTimeout = new JTextField( 3 );
    protected JTextField jtfTimeAllowance = new JTextField( 3 );
    protected JTextField jtfTrials = new JTextField( 3 );
    protected JTextField jtfDelay = new JTextField( 10 );
    protected JTextField jtfId = new JTextField( 10 );
    protected JTextField jtfTester = new JTextField( 10 );
    protected JTextField jtfImageDir = new JTextField( 3 );
    protected JTextField jtfDelayConstant = new JTextField( 3 );
    protected JTextField jtfiti = new JTextField( 3 );
    protected JTextField jtfDelayRangeStart = new JTextField( 3 );
    protected JTextField jtfDelayRangeEnd = new JTextField( 3 );
    protected JTextField jtfDelayInterval = new JTextField( 3 );
    protected JTextField jtfVD = new JTextField( 3 );
    protected JTextField jtfVT = new JTextField( 3 );
    protected JTextField jtfCS = new JTextField( 3 );
    protected JTextField jtfIS = new JTextField( 3 );
    protected JTextField jtDB = new JTextField( 3 );
    protected JTextField jtfCustom1 = new JTextField( 10 );
    protected JTextField jtfCustom2 = new JTextField( 10 );
    protected JTextField jtfCustom3 = new JTextField( 10 );
    protected JTextField jtfCustom4 = new JTextField( 10 );
    protected JTextField jtfCustom5 = new JTextField( 3 ); //this one is for number before shift

    protected JComboBox chooser;
    protected JComboBox chooser2;
    protected JComboBox chooser3;
    protected JComboBox chooser4;
    protected JComboBox chooser5;
    protected JComboBox chooser6;
    protected JComboBox chooser7;
    protected JComboBox chooser8;
    protected JComboBox chooser9;
    protected JComboBox chooser10;
    protected JComboBox chooser11;
    protected JComboBox chooser12;
    protected JComboBox chooser13; //for Custom CSST
    protected JComboBox chooser14; //increased delay toggle
    protected JComboBox correctionChooser; //for correction procedure

    private JButton startB;
    private JButton exitB;
    private JButton Choose = new JButton("Select");
    private JButton Choose2 = new JButton("Select");
    private JButton Choose3 = new JButton("Select");
    private JButton Choose4 = new JButton("Select");
    private JButton Choose5 = new JButton("Select");


    protected JLabel jlVersion = new JLabel("Version:");
    private JLabel blank1 = new JLabel(" ");
    private JLabel blank2 = new JLabel(" ");
    private JLabel blank3 = new JLabel(" ");
    private JLabel blank4 = new JLabel(" ");
    private JLabel blank6 = new JLabel(" ");
    private JLabel jliti = new JLabel("Inter-trial Interval:");
    private JLabel jloutput = new JLabel("Output To File:");
    private JLabel jltOut = new JLabel("Time out length:");
    private JLabel jltAllowance = new JLabel("Time Allowance:");
    private JLabel jlTrials = new JLabel("Number of trials:");
    private JLabel jlDate = new JLabel("Date:");
    private JLabel jlId = new JLabel("Monkey ID:");
    private JLabel jlTester = new JLabel("Tester:");
    private JLabel jlImageDir = new JLabel("Image Directory:");
    private JLabel jlDelay = new JLabel("Delay:");
    private JLabel jlDelayConstant = new JLabel("Fixed:");
    private JLabel jlDelayRange = new JLabel("Range:");
    private JLabel jlDelayRangeStart = new JLabel("From:");
    private JLabel jlDelayRangeEnd = new JLabel("To:");
    private JLabel jlDelayFile = new JLabel("File:");
    private JLabel jlScreenSize = new JLabel("Screen Size:");
    private JLabel jlDelayInterval = new JLabel("Interval:");
    private JLabel jlColor = new JLabel("Time Out Color:");
    private JLabel jlValidClick = new JLabel("Non-image clicks:");
    private JLabel jlCS = new JLabel("Correct Sound:");
    private JLabel jlIS = new JLabel("Incorrect Sound:");
    private JLabel jlReward = new JLabel("Reward:");
    private JLabel jlOP = new JLabel("Output Port:");
    private JLabel jlC = new JLabel("Cursor:");
    private JLabel jlCorrectProc = new JLabel("Correction Procedure:");
    private JLabel jlVD = new JLabel("Valve Delay:");
    private JLabel jlVT   = new JLabel("Valve Time:");
    private JLabel jlDB = new JLabel("Database Host:");
    private JLabel jlCustom1 = new JLabel("Conceptual Set 1:");
    private JLabel jlCustom2 = new JLabel("Conceptual Set 2:");
    private JLabel jlCustom3 = new JLabel("Conceptual Set 3:");
    private JLabel jlCustom4 = new JLabel("Conceptual Set 4:");
    private JLabel jlCustom5 = new JLabel("Number of Stimuli:");
    private JLabel jlCustom6 = new JLabel("Shift After:");
    protected JLabel jlProgressiveDelays = new JLabel("Progressive Delays:");
    private GridBagConstraints gbc;
    private GridBagLayout gbl;

    private final String[] programs = {"Shaping - centered", "Shaping - random location", "Matching to sample - DMS",
                                       "Non-Matching to sample - DNMS", "Spatial - DRST", "Object - DRST",
                                       "Progressive Ratio", "Delayed Response",
                                       "Attention Tasks", "Conceptual Set Shifting", "Custom CSST" };


    private final String[] reward = {"None", "Positive", "Negative", "Both"};
    private final String[] random = {"Fixed", "Random", "From File"};
    private final String[] ccst = {"Discrimination", "Full - Level 1", "Full - Level 2", "Full - Level 3", "Full - Level 4"};
    private final String[] yesno = {"Yes", "No"};
    private final String[] allowDisallow = {"Allowed", "Disallowed"};
    private final String[] cursorChoice = {"Blank", "Default"};
    private final String[] screenSize = {"1024x768", "800x600"};
    private final String[] theColor = {"Black", "Blue", "Gray", "Green", "Orange", "Pink", "Yellow"};
    private final String[] PR = {"Fixed Ratio 1", "Fixed Ratio 2", "Fixed Ratio 3",
                                  "Fixed Ratio 4", "Fixed Ratio 5", "Fixed Ratio 6",
                                  "Progressive Ratio", };
    private final String[] attention = {"Training", "Simple Search Easy", "Simple Search Hard", "Cued Search"};
    private final String[] OP = {"COM1", "COM2", "COM3", "COM4", "LPT1", "LPT2", "USB" };
    private Dimension size = new Dimension ( 750 /*675*/, 525 );

    private final String[] cardChoice = {"Standard", "Card", "Standard - One Line", "Card - One Line", "Card - Alternate Colors" };
    private JLabel cardLabel = new JLabel("Mode:");
    private final String[] customNumber = { "2", "3", "4", "5", "6", "7", "8", "9" };
    private final String[] progressiveDelays = { "Enabled", "Disabled" };

    private final String[] correctionProcedures = { "force", "off", "on" };

    // Handlers
    private ProgramSelectorHandler Handle;
    private QuitHandler QHandle;
    private ChooserHandler CHandle;
    private ChooserHandler CHandle2;
    private ChooserHandler CHandle3;
    private ChooserHandler CHandle4;
    private ChooserHandler CHandle5;
    private SaveLoadHandler sHandle;
    private SaveLoadHandler lHandle;
    private AboutHandler about;
    private ConvertHandler convert;
    private Calendar c;

    /** Creates new ProgramSelector */
    public ProgramSelector() {
        this.setIconImage( new ImageIcon(getClass().getRes
public Base(Vector images, JFrame window, int program, String p, int theDelay,
               int tallow, String date, String id, String tester, int tr, float[] d, String outFile,
               String imageDir, String screenSize, int c, int v, int fr, String ititemp, String VD, String VT,
               int at, int v2, int rgb, int port, int cursor, int crd, Clip CS, Clip IS, String db, String custom1,
               String custom2, String custom3, String custom4, int stim, int shfts, int progDel, int corProc )

Holy... that's a long constructor.

Try something like this in the 'if' blocks:

if (getKeyCode() == KeyEvent.VK_Q)
{
     //code to quit goes here
}
//etc...

Holy... that's a long constructor.

In deed. There's a number of things I'd do differently if I were to make it myself, and considering how difficult some of it is to format, I'm considering remaking it anyway. Well obviously, if some of it isn't working...

Try something like this in the 'if' blocks:

if (getKeyCode() == KeyEvent.VK_Q)
{
     //code to quit goes here
}
//etc...

Where would that go? Oh, lemme see...
Unfortunately, for whatever reason, it isn't actually entering the KeyPressed,-Typed, or -Released, (I have println statements inside all of them).

Is there an example somewhere of what a good constructor including keylistener looks like, and what the expected behavior would be? The only things I can think are something else grabbing the focus when I'm not looking or maybe I'm not adding the keylistener to the right place. The mouse operates on it just fine, so I /think/ it still has focus...

Hm. Just thought of a way to check if the Base has the focus... no, I did a "if Base.hasFocus() println("the Base has focus"), else println("lacks focus"), and apparently it lacks focus. But it's still reading the mouseclicks somewhere, because I set that part to run with the mouseclicks. Now what's stealing it and how do I get it to stop? Base is the last thing I explicitly add Focus to.

I'm going back to hunting, I guess. Do you folks have any suggestions for how to catch such a thing? Is there a command that says what has the focus?

Okay, I figured out the Base isn't getting the focus in the first place. I tried the code

this.show();
if(this.isDisplayable()) System.out.println("Displayable");
if(this.isVisible()) System.out.println("Visible");
this.setFocusable(true);
if(this.isFocusable()) System.out.println("Focusable");
buf = new BufferedImage(w , h, BufferedImage.TYPE_INT_RGB);
g2 = buf.createGraphics();
if(this.requestFocusInWindow()) System.out.println("Focus gained!");
else System.out.println("Lacks focus");

and got "Displayable" "Visible" "Focusable" "Lacks focus". Now I guess I figure out what other conditions I need for requestFocusInWindow to work?

I don't know whether anyone's still reading this, but I ended up changing the JWindow to an undecorated JFrame, which fixed the focus problem and hence the keylistener. It's behaving as expected now. Case closed.

hi
did you try running in other UI modes such as motif or windows?
Regards
Srinivas

hi
did you try running in other UI modes such as motif or windows?
Regards
Srinivas

As a JFrame or JWindow? Either way, I just ran it in Windows XP. UI = user interface?

hi
sorry to use a wrong word UI Mode, I meant Look And Feel. Try setting Motif or Windows Look And Feel.
Cheers
Srinivas

hi
sorry to use a wrong word UI Mode, I meant Look And Feel. Try setting Motif or Windows Look And Feel.
Cheers
Srinivas

It's actually undecorated right now; I'm trying to copy the same look and feel as a JWindow, so no borders or buttons or whatnot.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.