Dynamically Positioning the Control (Visual J++)

Take the following steps to dynamically scale and position the LEAD control when loading an image. This example scales the control to use most of the form's area while preserving the image's aspect ratio.

1. Start with the project that you created in Loading and Displaying an Image.

2. Modify the LeadLoad button's click procedure so that it appears as follows. For a general explanation of how images are positioned and scaled, refer to Displaying an Image.

private void LoadLead_click(Object source, Event e)
{
   // Position and size the main form so that it takes up most of the screen.
   Rectangle r = SystemInformation.getWorkingArea();
   setWidth ( (int) ( r.width * 0.9f ) );
   setHeight( (int) ( r.height * 0.8f ) );
   setLeft( ( r.width - getWidth() ) / 2 );
   setTop( ( r.height - getHeight() ) / 2 );

   //Turn off automated behavior while we load and manipulate the image.
   LEAD1.setAutoSetRects( false );
   LEAD1.setAutoRepaint( false );
   LEAD1.setAutoScroll( false );
   LEAD1.setBackErase( false );

   // Load the bitmap. This hard-coded path name may be different on your system.
   LEAD1.Load( "c:\\lead\\images\\image1.cmp", (short) 0, (short) 0, (short) 1 );

   // Set the variables used for preserving the aspect ratio.
   // Allow for a border of 1/8 of the form size.
   // The units of measure do not matter, since we are calculating proportions.
   int nHeightFactor = (int) LEAD1.getBitmapHeight();
   int nWidthFactor = (int) LEAD1.getBitmapWidth();
   int nHeightAllowed = getSize().y * 3/4;
   int nWidthAllowed = getSize().x * 3/4;

   // Center the LEAD control on the form, preserving the aspect ratio.
   // Check to see if using the maximum width will make the image too tall.
   // Set the dimensions based on the result.
   if( ( ( nWidthAllowed * nHeightFactor) / nWidthFactor) < nHeightAllowed )
   {
      LEAD1.setLeft( getSize().x / 8 );
      LEAD1.setWidth( nWidthAllowed );
      LEAD1.setHeight( ( LEAD1.getWidth() * nHeightFactor) / nWidthFactor );
      LEAD1.setTop( ( getSize().y - LEAD1.getHeight() ) / 2 );
   }
   else
   {
      LEAD1.setTop( getSize().y / 8 );
      LEAD1.setHeight( nHeightAllowed );
      LEAD1.setWidth( ( LEAD1.getHeight() * nWidthFactor) / nHeightFactor );
      LEAD1.setLeft( ( getSize().x - LEAD1.getWidth() ) / 2 );
   }

   // Set the image display size to match the LEAD control
   LEAD1.SetDstRect( 0, 0, LEAD1.getScaleWidth(), LEAD1.getScaleHeight() );
   LEAD1.SetDstClipRect( 0, 0, LEAD1.getScaleWidth(), LEAD1.getScaleHeight() );

   // Turn on automated behavior while we load and manipulate the image.
   LEAD1.setAutoSetRects( true );
   LEAD1.setAutoRepaint( true );
   LEAD1.setAutoScroll( true );
}

3. Run your program to test it.