[Tex/LaTex] Smaller frame with listings

beamerframedlistings

I am using listings to put java code in my beamer slides.

Sometimes, I want to frame the code but I do not want the frame to occupy
the whole width of the page. I want the frame to occupy only the width of
my code and no more.

Is there a way to do that?

Best Answer

Here is a solution with fancyvrb and output with listings:

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{beramono}
\usepackage[english]{babel}
\usepackage{blindtext}
\usepackage{fancyvrb}
\usepackage{listings}
\makeatletter
\newenvironment{SmallListing}[1][]
  {\lstset{#1}\VerbatimEnvironment\begin{VerbatimOut}{VerbEnv.tmp}}
  {\end{VerbatimOut}\settowidth\@tempdima{%
    \lstinputlisting{VerbEnv.tmp}}
  \minipage{\@tempdima}\lstinputlisting{VerbEnv.tmp}\endminipage}    
\makeatother
\begin{document}

\blindtext

\begin{center}
\begin{SmallListing}
  [language=Java,frame=single,columns=fixed,
   basicstyle=\small\ttfamily,
   keywordstyle=\bfseries]
static void main () {
  int foo;
  string baz;
}
\end{SmallListing}
\end{center}

\end{document}

enter image description here