Document Classes[Listings]Multiline caption in floating listing environment

Information and discussion about specific document classes and how to create your own document classes.
Post Reply
-Robin-
Posts: 31
Joined: Tue May 20, 2008 3:07 pm

[Listings]Multiline caption in floating listing environment

Post by -Robin- »

I was trying to have a multiline caption in the listing environment, but I can't get it working the way it should.
I found a suggestion on this forum that including the caption package should do it, but it didn't help me in a listing environment

Code: Select all

\documentclass{book}
\usepackage{listings}
\usepackage{caption}
\begin{document}
\lstinputlisting[float, caption={testcaption\\ multiline}, label={testlabel}]{sample.java}
\end{document}
Replacing the \\ by \newline generates a new line, but then the alignment is broken

Since Java files are not allowed to be attachted, I included the code in a code environment

Code: Select all

class Sample{
	private Object fVariable = new Object();

	public static void main(String[] args){
		int w = 0;
		boolean bool = true;
		for(int i = 0; i<w; i++){
			if(bool){
				System.out.println("Testing of the listing package");
			} else{
				/* Some blockcomments
				 * More comments
				 * And the last line of comments
				 */
				System.out.println("This code makes absolutely no sense");
			}
		}
	}
	public Object getVariable(){
		//Some testcomment
		return fVariable;
	}
}
Any suggestions
Attachments
testnonstyleusing.tex
The tex file
(193 Bytes) Downloaded 334 times

Recommended reading 2024:

LaTeXguide.org • LaTeX-Cookbook.net • TikZ.org

NEW: TikZ book now 40% off at Amazon.com for a short time.

User avatar
Juanjo
Posts: 657
Joined: Sat Jan 27, 2007 12:46 am

[Listings]Multiline caption in floating listing environment

Post by Juanjo »

Try this:

Code: Select all

\newsavebox{\captionbox}
\sbox{\captionbox}{\parbox[t]{\linewidth}{A very, very long caption here}}
\lstinputlisting[float, caption=\usebox{\captionbox}, label={testlabel}]{sample.java}
The CTAN lion is an artwork by Duane Bibby. Courtesy of www.ctan.org.
-Robin-
Posts: 31
Joined: Tue May 20, 2008 3:07 pm

Re: [Listings]Multiline caption in floating listing environment

Post by -Robin- »

Thanks. This solves my problem.

I had experimented myself with mbox but then it was impossible to set the width
User avatar
Juanjo
Posts: 657
Joined: Sat Jan 27, 2007 12:46 am

[Listings]Multiline caption in floating listing environment

Post by Juanjo »

-Robin- wrote: I had experimented myself with mbox but then it was impossible to set the width
Line breaks are disabled inside \mbox, so it would be useless. Just for your records, if you want to set the width, use \makebox[width]{text}.
The CTAN lion is an artwork by Duane Bibby. Courtesy of www.ctan.org.
Post Reply