You can use \begin{lstlisting}[xleftmargin=5.0ex]
to adjust the left margin, or add this option to \lstset
. This will move your listing to the right including the lines numbers and any frames.
The lipsum
package is used to provide some dummy text before the listing. I also included the geometry
package with [showframe]
option to see the margins.

\documentclass{article}
\usepackage[showframe]{geometry}
\usepackage{lipsum}
\usepackage{listings}
\begin{document}
\lipsum[1]
\begin{figure}[!htbp]
\setlength{\fboxsep}{0pt}%
\setlength{\fboxrule}{0pt}%
%\begin{center}
\centering
\lstset{language=Java, numbers=left, showspaces=false,
showstringspaces=false, tabsize=2, breaklines=true,
xleftmargin=5.0ex,
%numberstyle=\scriptsize,numbersep=0pt
}
\begin{lstlisting}
public class AutoRegistry {
public void registerCar(int ssn, int vin) {
// ...
PersonCarDirect personCar = new PersonCarDirect();
personCar.setId(ssn);
personCar.setVin(vin);
// ...
}
}
\end{lstlisting}
%\end{center}
%\vspace{-12pt}
\caption{AutoRegistry client class}
\label{fig:autoRegistryClientC}
\end{figure}
\end{document}
As pointed out by @Mico, you should use \centering
instead of \begin{center}...\end{center}
. This would also allow you to eliminate the \vspace{-12pt}
. See Should I use center or centering for figures and tables? for more details. In case someone copies the above code and does not read the other solutions, I have made those changes in the code, and left your original code as comments.
Align Number to just right of column
If you are tight on space and want to align the numbers just to the right of the column, then use:
\newlength{\MaxSizeOfLineNumbers}%
\settowidth{\MaxSizeOfLineNumbers}{99}% Adjust to maximum number of lines
\addtolength{\MaxSizeOfLineNumbers}{2.5ex}%
and set:
xleftmargin=\MaxSizeOfLineNumbers
The 2.5ex
is the adjustment that gets the numbers just to the left of the margin, and we shift over by the width of the digits 99
.
This of course assumes that the number of lines in your listings is less than 100, so adjust accordingly. Also, if you happen to change the number style using something like numberstyle=\tiny
, the {99}
parameter should be adjusted accordingly to {\tiny 99}
.