7

I'd like to ask how I can add a line break in a multipart rectangle node.

Code that I've written should work but it is not. Can you tell me what I have done wrong, or how can I tune it to make it work.

\tikzstyle{umlclass}=[
    draw=black,
    fill=yellow!16,
    rectangle split,
    rectangle split parts = 3,
    rectangle split part align={center,left,left},
    execute at begin node = \ttfamily,
]   
\node[umlclass]{
    <<interface>>\\
    class
    \nodepart{second}
    +attribute
};
David Carlisle
  • 757,742

2 Answers2

5

You could simply use a \parbox. You still could use \centering for the alignment, if desired. Furthermore it's recommended to use \tikzset instead of \tikzstyle.

\documentclass[10pt]{book}
\usepackage{tikz}
\usetikzlibrary{shapes.multipart}
\tikzset{umlclass/.style={
    draw=black,
    fill=yellow!16,
    rectangle split,
    rectangle split parts = 3,
    rectangle split part align={center,left,left},
    execute at begin node = \ttfamily,
}}
\begin{document}
\begin{tikzpicture}

\node[umlclass]{
    \parbox{2.4cm}{\centering
      <<interface>>\\
      class}
    \nodepart{second}
    +attribute
};
\end{tikzpicture}
\end{document}

UML node

The very good comment of egreg, to use a tabular to not need to know the width:

\node[umlclass]{
    \begin{tabular}{@{}c@{}}
      <<interface>>\\
      class
    \end{tabular}
    \nodepart{second}
    +attribute
};

UML node

Moriambar
  • 11,466
Stefan Kottwitz
  • 231,401
5

You have to supply align=center to the general node options, as the first node part isn't treated like the others. The rectangle split part align option does apply to it, but only affects the box that uses the align option internally (which is also the reason \\ hasn’t the expected effect).

That means that one need to specify align=center and rectangle split part align={center,…}

enter image description here

\documentclass[border=5mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{shapes.multipart,positioning}
\tikzset{
    umlclass/.style={
        draw=black,fill=yellow!16,rectangle split,rectangle split parts = 3,font = \ttfamily},
    umlclass -c/.style={
        umlclass,align=center,rectangle split part align={left}},         % = left,   left, left
    umlclass -r/.style={
        umlclass,align=right, rectangle split part align={left}},         % = left,   left, left
    umlclass +/.style={
        umlclass,align=center, rectangle split part align={center,left}}} % = center, left, left
\newcommand*{\umlclasscontent}{<<interface>>\\class\nodepart{second}very long attribute\nodepart{third}method()}
\begin{document}
\begin{tikzpicture}
\node[umlclass -c]           {\umlclasscontent};
\node[umlclass -r] at (0,-3) {\umlclasscontent};
\node[umlclass +]  at (0,-6) {\umlclasscontent};
\end{tikzpicture}
\end{document}
Qrrbrbirlbel
  • 119,821
Jake
  • 232,450