code: public static Dimension dimensionsToFit(Dimension target, Dimension source) {
  
          // if target width/height is zero then we have no preference for that, so set it to the original value,
          // since it cannot be any larger
          int maxWidth;
          if (target.getX() == 0) {
              maxWidth = source.getX();
          } else {
              maxWidth = target.getX();
          }
  
          int maxHeight;
          if (target.getY() == 0) {
              maxHeight = source.getY();
          } else {
              maxHeight = target.getY();
          }
  
          double wscale = maxWidth / (double) source.getX();
          double hscale = maxHeight / (double) source.getY();
  
          if (wscale < hscale)
              return new Dimension((int) (source.getX() * wscale), (int) (source.getY() * wscale));
          else
              return new Dimension((int) (source.getX() * hscale), (int) (source.getY() * hscale));
      }
docs: Returns width and height that allow the given source width, height to fit inside the target width, height
  without losing aspect ratio