将列表代码嵌入到表中吗?

将列表代码嵌入到表中吗?

在这种情况下,我想创建一个简单的表格,其中第一列包含代码片段,第二列对其进行描述。

命令 \java 定义如下:

\newcommand{\java}{\begin{lstlisting}[language=Java]}

整行都变成了我的java代码的风格。

\begin{tabular}{l|l}
\java
private
\end{lstlisting}
&   Only entities declared inside the class are allowed to refer to private symbols \\

\java
protected
\end{lstlisting}
&   Entities declared inside the class or children of the class \\

\java
public
\end{lstlisting}
&   Everyone is allowed to refer to public symbols          \\

default (no qualifier specified)
&   Entities in the class, children of the class, or anyone in the same package are allowed access.
\end{tabular}

答案1

另一种方法是使用collcell包并为 Java 代码定义新的列类型。正如 Jubobs 在评论中指出的那样,如果单元格包含非代码,格式将不正确。您需要使用 覆盖其规范\multicolumn。如果同一列中混合了代码和非代码,那么像他这样的解决方案显然更好。

\documentclass{article}
\usepackage{array}
\usepackage{listings}
\usepackage{collcell}
\newcommand\java[1]{{\lstinline[language=java]{#1}}}
\newcolumntype{J}{>{\collectcell\java}l<{\endcollectcell}}

\begin{document}

\begin{tabular}{J|p{2in}} 
private
&   Only entities declared inside the class are allowed to refer to private symbols \\
protected
&   Entities declared inside the class or children of the class \\
public
&   Everyone is allowed to refer to public symbols          \\
\multicolumn{1}{l|}{default (no qualifier specified)}
&   Entities in the class, children of the class, or anyone in the same package are allowed access.
\end{tabular}
\end{document}

在此处输入图片描述

答案2

建议:使用内联代码而不是lstlisting环境,并且为了方便起见,使用单字符简写。

在此处输入图片描述

\documentclass{article}

\usepackage{listings}
\lstMakeShortInline[language=Java,basicstyle=\ttfamily]`

\begin{document}

\begin{tabular}{l|p{7cm}}
`private`
  &   Only entities declared inside the class are allowed to refer to private symbols \\
`protected`
  &   Entities declared inside the class or children of the class \\
`public`
  &   Everyone is allowed to refer to public symbols          \\
default (no qualifier specified)
  &   Entities in the class, children of the class, or anyone in the same package are allowed access.
\end{tabular}

\end{document}

相关内容