[Tex/LaTex] Using listings package with beamer/block environments for displaying source code

beamerlistingssourcecode

I use beamer with semiverbatim environment to show source code.

\documentclass{beamer}
\setbeamercolor{background canvas}{bg=yellow}
\useinnertheme[shadow]{rounded}
\setbeamercolor{block title example}{fg=white,bg=red!75!black}%
\setbeamercolor{block body example}{fg=black,bg=white!70!red}%

\begin{document}

\begin{frame}[fragile]{Code}
\begin{example}[Code]
\begin{semiverbatim}
class Hello {
...
}
\end{semiverbatim}
\end{example}
    \end{frame}
\end{document}

enter image description here

However, I want listings package which provides features such as highlighting and source code numbering. So, I tried this.

\documentclass{beamer}
\setbeamercolor{background canvas}{bg=yellow}
\useinnertheme[shadow]{rounded}

\usepackage{listings}

\lstset{numbers=left, numberstyle=\tiny, stepnumber=1,firstnumber=1,
    numbersep=5pt,language=Java,
    stringstyle=\ttfamily,
    basicstyle=\footnotesize, 
    showstringspaces=false
}

\begin{document}

\begin{frame}[fragile]{Code}

\begin{block}
\begin{lstlisting}[firstnumber=1, caption=Getting labels, label=glabels] 

class Hello {
...
}

\end{lstlisting}
\end{block}

\end{frame}
\end{document}

However, I can't compile it to get an output.

My questions are:

  1. How can I use listings package with beamer/blocks?
  2. Or how can I show source code with line number listing and keyword highlighting with beamer/blocks?

Best Answer

Beamer blocks need a title (\begin{block}{_title_}), even if it is empty (\begin{block}{}).

\documentclass{beamer}
\setbeamercolor{background canvas}{bg=yellow}
\useinnertheme[shadow]{rounded}

\usepackage{listings}

\lstset{numbers=left, numberstyle=\tiny, stepnumber=1,firstnumber=1,
    numbersep=5pt,language=Java,
    stringstyle=\ttfamily,
    basicstyle=\footnotesize, 
    showstringspaces=false
}

\begin{document}

\begin{frame}[fragile]{Code}

\begin{block}{Getting labels}
\begin{lstlisting}[firstnumber=1, label=glabels, xleftmargin=10pt] 
class Hello {
...
}
\end{lstlisting}
\end{block}

\end{frame}
\end{document}

enter image description here

Related Question