Welcome to TeX.SX!
Yes, I would indeed say there is a better way of achieving this. Well, at least in my humble opinion.
For starters, as has been mentioned by TeXnician, using a figure to contain a listing isn't really very proper. I would recommend using dedicated listings
environments for that. After all, a figure is not the same thing as a listing.
Besides the philosophical question of whether or not one should use figure
environments to contain listings, there is also a practical issue: A figure
environment is a float and cannot break across pages. So I would recommend a different approach:
- Use a
listings
float for short code listings which should not break across pages.
- Create a new environment for long code listings which can break across pages. See page 32 of the
minted
package documentation, which also refers to this question.
Short Example for Showcasing the Principles
As said, we create a new environment called longlisting
which will break across pages and can be captioned and labelled. It will also show up in the \listoflistings
.
\documentclass{article}
\usepackage{minted}
\usepackage{caption}
\setminted{
linenos=true,
autogobble,
}
% Create a new environment for breaking code listings across pages.
\newenvironment{longlisting}{\captionsetup{type=listing}}{}
\begin{document}
\listoflistings
\section{Let Us Make Some Listings}
\begin{longlisting}
\begin{minted}{tex}
... input a lot of code here ...
... It will break across pages ...
\end{minted}
\caption[Long Code Example]{A long code example which will break across pages.}
\label{lst:long}
\end{longlisting}
\begin{listing}
\begin{minted}{java}
... input short code here ...
... This code will not break across pages ...
\end{minted}
\caption[Short Code Example]{A shorter code example which will not break across pages.}
\label{lst:short}
\end{listing}
\end{document}
Result When Filled in With of Code

Closing Remarks
Apologies if I have misunderstood your intent. If you truly do want to list your listings as figure
s, you can make the following changes in my code:
Instead of
\newenvironment{longlisting}{\captionsetup{type=listing}}{}
write:
\newenvironment{longlisting}{\captionsetup{type=figure}}{}
And for the non-breakable environments, just use figure
as you have been doing. But as said, I would really not recommend this.
\captionof{figure}{My caption}
. In order to give you real advice please post some more code (MWE). – TeXnician May 9 '17 at 14:46