Class Label

All Implemented Interfaces:
Accessible, AccessibleHypertext, AccessibleText, Buildable, ConstraintTarget, Proxy

@Generated("org.javagi.JavaGI") public class Label extends Widget implements Accessible, AccessibleHypertext, AccessibleText, Buildable, ConstraintTarget

Displays a small amount of text.

Most labels are used to label another widget (such as an Entry).

An example GtkLabel

Shortcuts and Gestures

GtkLabel supports the following keyboard shortcuts, when the cursor is visible:

  • Shift+F10 or Menu opens the context menu.
  • Ctrl+A or Ctrl+/ selects all.
  • Ctrl+Shift+A or Ctrl+\ unselects all.

Additionally, the following signals have default keybindings:

  • Gtk.Label::activate-current-link
  • Gtk.Label::copy-clipboard
  • Gtk.Label::move-cursor

Actions

GtkLabel defines a set of built-in actions:

  • clipboard.copy copies the text to the clipboard.
  • clipboard.cut doesn't do anything, since text in labels can't be deleted.
  • clipboard.paste doesn't do anything, since text in labels can't be edited.
  • link.open opens the link, when activated on a link inside the label.
  • link.copy copies the link to the clipboard, when activated on a link inside the label.
  • menu.popup opens the context menu.
  • selection.delete doesn't do anything, since text in labels can't be deleted.
  • selection.select-all selects all of the text, if the label allows selection.

CSS nodes

label
├── [selection]
├── [link]
┊
╰── [link]

GtkLabel has a single CSS node with the name label. A wide variety of style classes may be applied to labels, such as .title, .subtitle, .dim-label, etc. In the GtkShortcutsWindow, labels are used with the .keycap style class.

If the label has a selection, it gets a subnode with name selection.

If the label has links, there is one subnode per link. These subnodes carry the link or visited state depending on whether they have been visited. In this case, label node also gets a .link style class.

GtkLabel as GtkBuildable

The GtkLabel implementation of the GtkBuildable interface supports a custom <attributes> element, which supports any number of <attribute> elements. The <attribute> element has attributes named “name“, “value“, “start“ and “end“ and allows you to specify Pango.Attribute values for this label.

An example of a UI definition fragment specifying Pango attributes:

<object class="GtkLabel">
  <attributes>
    <attribute name="weight" value="PANGO_WEIGHT_BOLD"/>
    <attribute name="background" value="red" start="5" end="10"/>
  </attributes>
</object>

The start and end attributes specify the range of characters to which the Pango attribute applies. If start and end are not specified, the attribute is applied to the whole text. Note that specifying ranges does not make much sense with translatable attributes. Use markup embedded in the translatable content instead.

Accessibility

GtkLabel uses the Gtk.AccessibleRole.label role.

Mnemonics

Labels may contain “mnemonics”. Mnemonics are underlined characters in the label, used for keyboard navigation. Mnemonics are created by providing a string with an underscore before the mnemonic character, such as "_File", to the functions withMnemonic(String) or setTextWithMnemonic(String).

Mnemonics automatically activate any activatable widget the label is inside, such as a Button; if the label is not inside the mnemonic’s target widget, you have to tell the label about the target using setMnemonicWidget(Widget).

Here’s a simple example where the label is inside a button:

// Pressing Alt+H will activate this button
GtkWidget *button = gtk_button_new ();
GtkWidget *label = gtk_label_new_with_mnemonic ("_Hello");
gtk_button_set_child (GTK_BUTTON (button), label);

There’s a convenience function to create buttons with a mnemonic label already inside:

// Pressing Alt+H will activate this button
GtkWidget *button = gtk_button_new_with_mnemonic ("_Hello");

To create a mnemonic for a widget alongside the label, such as a Entry, you have to point the label at the entry with setMnemonicWidget(Widget):

// Pressing Alt+H will focus the entry
GtkWidget *entry = gtk_entry_new ();
GtkWidget *label = gtk_label_new_with_mnemonic ("_Hello");
gtk_label_set_mnemonic_widget (GTK_LABEL (label), entry);

Markup (styled text)

To make it easy to format text in a label (changing colors, fonts, etc.), label text can be provided in a simple markup format:

Here’s how to create a label with a small font:

GtkWidget *label = gtk_label_new (NULL);
gtk_label_set_markup (GTK_LABEL (label), "<small>Small text</small>");

(See the Pango manual for complete documentation] of available tags, Pango#parseMarkup)

The markup passed to setMarkup(String) must be valid XML; for example, literal <, > and & characters must be escaped as &lt;, &gt;, and &amp;. If you pass text obtained from the user, file, or a network to setMarkup(String), you’ll want to escape it with GLib#markupEscapeText or GLib#markupPrintfEscaped.

Markup strings are just a convenient way to set the Pango.AttrList on a label; setAttributes(AttrList) may be a simpler way to set attributes in some cases. Be careful though; Pango.AttrList tends to cause internationalization problems, unless you’re applying attributes to the entire string (i.e. unless you set the range of each attribute to Pango.Attribute requires knowledge of the exact string being displayed, so translations will cause problems.

Selectable labels

Labels can be made selectable with setSelectable(boolean). Selectable labels allow the user to copy the label contents to the clipboard. Only labels that contain useful-to-copy information — such as error messages — should be made selectable.

Text layout

A label can contain any number of paragraphs, but will have performance problems if it contains more than a small number. Paragraphs are separated by newlines or other paragraph separators understood by Pango.

Labels can automatically wrap text if you call setWrap(boolean).

setJustify(Justification) sets how the lines in a label align with one another. If you want to set how the label as a whole aligns in its available space, see the Gtk.Widget:halign and Gtk.Widget:valign properties.

The Gtk.Label:width-chars and Gtk.Label:max-width-chars properties can be used to control the size allocation of ellipsized or wrapped labels. For ellipsizing labels, if either is specified (and less than the actual text size), it is used as the minimum width, and the actual text size is used as the natural width of the label. For wrapping labels, width-chars is used as the minimum width, if specified, and max-width-chars is used as the natural width. Even if max-width-chars specified, wrapping labels will be rewrapped to use all of the available width.

GTK supports markup for clickable hyperlinks in addition to regular Pango markup. The markup for links is borrowed from HTML, using the <a> tag with “href“, “title“ and “class“ attributes. GTK renders links similar to the way they appear in web browsers, with colored, underlined text. The “title“ attribute is displayed as a tooltip on the link. The “class“ attribute is used as style class on the CSS node for the link.

An example of inline links looks like this:

const char *text =
"Go to the "
"<a href=\\"https://www.gtk.org\\" title=\\"&lt;i&gt;Our&lt;/i&gt; website\\">"
"GTK website</a> for more...";
GtkWidget *label = gtk_label_new (NULL);
gtk_label_set_markup (GTK_LABEL (label), text);

It is possible to implement custom handling for links and their tooltips with the Gtk.Label::activate-link signal and the getCurrentUri() function.

  • Constructor Details

    • Label

      public Label(MemorySegment address)
      Create a Label instance for the provided memory address.
      Parameters:
      address - the memory address of the native object
    • Label

      public Label(@Nullable String str)

      Creates a new label with the given text inside it.

      You can pass NULL to get an empty label widget.

      Parameters:
      str - the text of the label
    • Label

      public Label()
      Create a new Label.
  • Method Details

    • getType

      public static @Nullable Type getType()
      Get the GType of the Label class.
      Returns:
      the GType
    • getMemoryLayout

      public static MemoryLayout getMemoryLayout()
      The memory layout of the native struct.
      Returns:
      the memory layout
    • asParent

      protected Label asParent()
      Return this instance as if it were its parent type. Comparable to the Java super keyword, but ensures the parent typeclass is also used in native code.
      Overrides:
      asParent in class Widget
      Returns:
      the instance as if it were its parent type
    • withMnemonic

      public static Label withMnemonic(@Nullable String str)

      Creates a new label with the given text inside it, and a mnemonic.

      If characters in str are preceded by an underscore, they are underlined. If you need a literal underscore character in a label, use '__' (two underscores). The first underlined character represents a keyboard accelerator called a mnemonic. The mnemonic key can be used to activate another widget, chosen automatically, or explicitly using setMnemonicWidget(Widget).

      If setMnemonicWidget(Widget) is not called, then the first activatable ancestor of the label will be chosen as the mnemonic widget. For instance, if the label is inside a button or menu item, the button or menu item will automatically become the mnemonic widget and be activated by the mnemonic.

      Parameters:
      str - the text of the label, with an underscore in front of the mnemonic character
      Returns:
      the new label
    • getAttributes

      public @Nullable AttrList getAttributes()

      Gets the label's attribute list.

      This is the Pango.AttrList that was set on the label using setAttributes(AttrList), if any. This function does not reflect attributes that come from the label's markup (see setMarkup(String)). If you want to get the effective attributes for the label, use pango_layout_get_attributes (gtk_label_get_layout (self)).

      Returns:
      the attribute list
    • getCurrentUri

      public @Nullable String getCurrentUri()

      Returns the URI for the active link in the label.

      The active link is the one under the mouse pointer or, in a selectable label, the link in which the text cursor is currently positioned.

      This function is intended for use in a Gtk.Label::activate-link handler or for use in a Gtk.Widget::query-tooltip handler.

      Returns:
      the active URI
    • getEllipsize

      public EllipsizeMode getEllipsize()

      Returns the ellipsization mode of the label.

      See setEllipsize(EllipsizeMode).

      Returns:
      the ellipsization mode
    • getExtraMenu

      public @Nullable MenuModel getExtraMenu()

      Gets the extra menu model of the label.

      See setExtraMenu(MenuModel).

      Returns:
      the menu model
    • getJustify

      public Justification getJustify()

      Returns the justification of the label.

      See setJustify(Justification).

      Returns:
      the justification value
    • getLabel

      public String getLabel()

      Fetches the text from a label.

      The returned text includes any embedded underlines indicating mnemonics and Pango markup. (See getText()).

      Returns:
      the text of the label widget
    • getLayout

      public Layout getLayout()

      Gets the Pango layout used to display the label.

      The layout is useful to e.g. convert text positions to pixel positions, in combination with getLayoutOffsets(Out, Out). The returned layout is owned by the label so need not be freed by the caller. The label is free to recreate its layout at any time, so it should be considered read-only.

      Returns:
      the Layout for this label
    • getLayoutOffsets

      public void getLayoutOffsets(@Nullable Out<Integer> x, @Nullable Out<Integer> y)

      Obtains the coordinates where the label will draw its Pango layout.

      The coordinates are useful to convert mouse events into coordinates inside the Layout, e.g. to take some action if some part of the label is clicked. Remember when using the Layout functions you need to convert to and from pixels using PANGO_PIXELS() or Pango.SCALE.

      Parameters:
      x - location to store X offset of layout
      y - location to store Y offset of layout
    • getLines

      public int getLines()

      Gets the number of lines to which an ellipsized, wrapping label should be limited.

      See setLines(int).

      Returns:
      the number of lines
    • getMaxWidthChars

      public int getMaxWidthChars()

      Retrieves the maximum width of the label in characters.

      See setWidthChars(int).

      Returns:
      the maximum width of the label, in characters
    • getMnemonicKeyval

      public int getMnemonicKeyval()

      Return the mnemonic accelerator.

      If the label has been set so that it has a mnemonic key this function returns the keyval used for the mnemonic accelerator. If there is no mnemonic set up it returns GDK_KEY_VoidSymbol.

      Returns:
      GDK keyval usable for accelerators, or GDK_KEY_VoidSymbol
    • getMnemonicWidget

      public @Nullable Widget getMnemonicWidget()

      Retrieves the mnemonic target of this label.

      See setMnemonicWidget(Widget).

      Returns:
      the target of the label’s mnemonic, or NULL if none has been set and the default algorithm will be used.
    • getNaturalWrapMode

      public NaturalWrapMode getNaturalWrapMode()

      Returns natural line wrap mode used by the label.

      See setNaturalWrapMode(NaturalWrapMode).

      Returns:
      the natural line wrap mode
      Since:
      4.6
    • getSelectable

      public boolean getSelectable()
      Returns whether the label is selectable.
      Returns:
      true if the user can copy text from the label
    • getSelectionBounds

      public boolean getSelectionBounds(@Nullable Out<Integer> start, @Nullable Out<Integer> end)

      Gets the selected range of characters in the label.

      The returned start and end positions are in characters.

      Parameters:
      start - return location for start of selection
      end - return location for end of selection
      Returns:
      true if selection is non-empty
    • getSingleLineMode

      public boolean getSingleLineMode()
      Returns whether the label is in single line mode.
      Returns:
      true if the label is in single line mode
    • getTabs

      public @Nullable TabArray getTabs()

      Gets the tab stops for the label.

      The returned array will be NULL if “standard” (8-space) tabs are used.

      Returns:
      copy of default tab array, or NULL if standard tabs are used
      Since:
      4.8
    • getText

      public String getText()

      Gets the text of the label.

      The returned text is as it appears on screen. This does not include any embedded underlines indicating mnemonics or Pango markup. (See getLabel())

      Returns:
      the text in the label widget
    • getUseMarkup

      public boolean getUseMarkup()

      Returns whether the label’s text is interpreted as Pango markup.

      See setUseMarkup(boolean).

      Returns:
      true if the label’s text will be parsed for markup
    • getUseUnderline

      public boolean getUseUnderline()

      Returns whether underlines in the label indicate mnemonics.

      See setUseUnderline(boolean).

      Returns:
      true if underlines in the label indicate mnemonics
    • getWidthChars

      public int getWidthChars()

      Retrieves the desired width of the label in characters.

      See setWidthChars(int).

      Returns:
      the desired width of the label, in characters
    • getWrap

      public boolean getWrap()

      Returns whether lines in the label are automatically wrapped.

      See setWrap(boolean).

      Returns:
      true if the lines of the label are automatically wrapped
    • getWrapMode

      public WrapMode getWrapMode()

      Returns line wrap mode used by the label.

      See setWrapMode(WrapMode).

      Returns:
      the line wrap mode
    • getXalign

      public float getXalign()

      Gets the xalign of the label.

      See the Gtk.Label:xalign property.

      Returns:
      the xalign value
    • getYalign

      public float getYalign()

      Gets the yalign of the label.

      See the Gtk.Label:yalign property.

      Returns:
      the yalign value
    • selectRegion

      public void selectRegion(int startOffset, int endOffset)

      Selects a range of characters in the label, if the label is selectable.

      See setSelectable(boolean). If the label is not selectable, this function has no effect. If startOffset or endOffset are -1, then the end of the label will be substituted.

      Parameters:
      startOffset - start offset, in characters
      endOffset - end offset, in characters
    • setAttributes

      public void setAttributes(@Nullable AttrList attrs)

      Apply attributes to the label text.

      The attributes set with this function will be applied and merged with any other attributes previously effected by way of the Gtk.Label:use-underline or Gtk.Label:use-markup properties

      While it is not recommended to mix markup strings with manually set attributes, if you must; know that the attributes will be applied to the label after the markup string is parsed.

      Parameters:
      attrs - a list of style attributes
    • setEllipsize

      public void setEllipsize(EllipsizeMode mode)

      Sets the mode used to ellipsize the text.

      The text will be ellipsized if there is not enough space to render the entire string.

      Parameters:
      mode - the ellipsization mode
    • setExtraMenu

      public void setExtraMenu(@Nullable MenuModel model)
      Sets a menu model to add to the context menu of the label.
      Parameters:
      model - a menu model
    • setJustify

      public void setJustify(Justification jtype)

      Sets the alignment of lines in the label relative to each other.

      This function has no effect on labels containing only a single line.

      Gtk.Justification.left is the default value when the widget is first created with Label().

      If you instead want to set the alignment of the label as a whole, use Widget.setHalign(Align) instead.

      Parameters:
      jtype - the new justification
    • setLabel

      public void setLabel(String str)

      Sets the text of the label.

      The label is interpreted as including embedded underlines and/or Pango markup depending on the values of the Gtk.Label:use-underline and Gtk.Label:use-markup properties.

      Parameters:
      str - the new text to set for the label
    • setLines

      public void setLines(int lines)

      Sets the number of lines to which an ellipsized, wrapping label should be limited.

      This has no effect if the label is not wrapping or ellipsized. Set this to -1 if you don’t want to limit the number of lines.

      Parameters:
      lines - the desired number of lines, or -1
    • setMarkup

      public void setMarkup(String str)

      Sets the labels text and attributes from markup.

      The string must be marked up with Pango markup (see Pango#parseMarkup).

      If str is external data, you may need to escape it with GLib#markupEscapeText or GLib#markupPrintfEscaped:

      GtkWidget *self = gtk_label_new (NULL);
      const char *str = "...";
      const char *format = "<span style=\\"italic\\">\\%s</span>";
      char *markup;
      
      markup = g_markup_printf_escaped (format, str);
      gtk_label_set_markup (GTK_LABEL (self), markup);
      g_free (markup);
      

      This function sets the Gtk.Label:use-markup property to true.

      Also see setText(String).

      Parameters:
      str - the markup string
    • setMarkupWithMnemonic

      public void setMarkupWithMnemonic(String str)

      Sets the labels text, attributes and mnemonic from markup.

      Parses str which is marked up with Pango markup (see Pango#parseMarkup), setting the label’s text and attribute list based on the parse results. If characters in str are preceded by an underscore, they are underlined indicating that they represent a keyboard accelerator called a mnemonic.

      The mnemonic key can be used to activate another widget, chosen automatically, or explicitly using setMnemonicWidget(Widget).

      Parameters:
      str - the markup string
    • setMaxWidthChars

      public void setMaxWidthChars(int nChars)
      Sets the maximum width of the label in characters.
      Parameters:
      nChars - the new maximum width, in characters.
    • setMnemonicWidget

      public void setMnemonicWidget(@Nullable Widget widget)

      Associate the label with its mnemonic target.

      If the label has been set so that it has a mnemonic key (using i.e. setMarkupWithMnemonic(String), setTextWithMnemonic(String), withMnemonic(String) or the Gtk.Label:use_underline property) the label can be associated with a widget that is the target of the mnemonic. When the label is inside a widget (like a Button or a Notebook tab) it is automatically associated with the correct widget, but sometimes (i.e. when the target is a Entry next to the label) you need to set it explicitly using this function.

      The target widget will be accelerated by emitting the Gtk.Widget::mnemonic-activate signal on it. The default handler for this signal will activate the widget if there are no mnemonic collisions and toggle focus between the colliding widgets otherwise.

      Parameters:
      widget - the target widget
    • setNaturalWrapMode

      public void setNaturalWrapMode(NaturalWrapMode wrapMode)

      Selects the line wrapping for the natural size request.

      This only affects the natural size requested, for the actual wrapping used, see the Gtk.Label:wrap-mode property.

      Parameters:
      wrapMode - the line wrapping mode
      Since:
      4.6
    • setSelectable

      public void setSelectable(boolean setting)

      Makes text in the label selectable.

      Selectable labels allow the user to select text from the label, for copy-and-paste.

      Parameters:
      setting - true to allow selecting text in the label
    • setSingleLineMode

      public void setSingleLineMode(boolean singleLineMode)
      Sets whether the label is in single line mode.
      Parameters:
      singleLineMode - true to enable single line mode
    • setTabs

      public void setTabs(@Nullable TabArray tabs)
      Sets tab stops for the label.
      Parameters:
      tabs - tab stops
      Since:
      4.8
    • setText

      public void setText(String str)

      Sets the text for the label.

      It overwrites any text that was there before and clears any previously set mnemonic accelerators, and sets the Gtk.Label:use-underline and Gtk.Label:use-markup properties to false.

      Also see setMarkup(String).

      Parameters:
      str - the text to show in this Label
    • setTextWithMnemonic

      public void setTextWithMnemonic(String str)

      Sets the text for the label, with mnemonics.

      If characters in str are preceded by an underscore, they are underlined indicating that they represent a keyboard accelerator called a mnemonic. The mnemonic key can be used to activate another widget, chosen automatically, or explicitly using setMnemonicWidget(Widget).

      Parameters:
      str - the text
    • setUseMarkup

      public void setUseMarkup(boolean setting)

      Sets whether the text of the label contains markup.

      See setMarkup(String).

      Parameters:
      setting - true if the label’s text should be parsed for markup.
    • setUseUnderline

      public void setUseUnderline(boolean setting)
      Sets whether underlines in the text indicate mnemonics.
      Parameters:
      setting - true if underlines in the text indicate mnemonics
    • setWidthChars

      public void setWidthChars(int nChars)
      Sets the desired width in characters of the label.
      Parameters:
      nChars - the new desired width, in characters.
    • setWrap

      public void setWrap(boolean wrap)

      Toggles line wrapping within the label.

      True makes it break lines if text exceeds the widget’s size. false lets the text get cut off by the edge of the widget if it exceeds the widget size.

      Note that setting line wrapping to true does not make the label wrap at its parent widget’s width, because GTK widgets conceptually can’t make their requisition depend on the parent widget’s size. For a label that wraps at a specific position, set the label’s width using Widget.setSizeRequest(int, int).

      Parameters:
      wrap - whether to wrap lines
    • setWrapMode

      public void setWrapMode(WrapMode wrapMode)

      Controls how line wrapping is done.

      This only affects the label if line wrapping is on. (See setWrap(boolean))

      The default is Pango.WrapMode.word, which means wrap on word boundaries.

      For sizing behavior, also consider the Gtk.Label:natural-wrap-mode property.

      Parameters:
      wrapMode - the line wrapping mode
    • setXalign

      public void setXalign(float xalign)

      Sets the xalign of the label.

      See the Gtk.Label:xalign property.

      Parameters:
      xalign - the new xalign value, between 0 and 1
    • setYalign

      public void setYalign(float yalign)

      Sets the yalign of the label.

      See the Gtk.Label:yalign property.

      Parameters:
      yalign - the new yalign value, between 0 and 1
    • onActivateCurrentLink

      Gets emitted when the user activates a link in the label.

      The ::activate-current-link is a keybinding signal.

      Applications may also emit the signal with g_signal_emit_by_name() if they need to control activation of URIs programmatically.

      The default bindings for this signal are all forms of the Enter key.

      Parameters:
      handler - the signal handler
      Returns:
      a signal handler ID to keep track of the signal connection
      See Also:
    • emitActivateCurrentLink

      public void emitActivateCurrentLink()
      Emits the "activate-current-link" signal. See onActivateCurrentLink(Label.ActivateCurrentLinkCallback).
    • onActivateLink

      Gets emitted to activate a URI.

      Applications may connect to it to override the default behaviour, which is to call FileLauncher.launch(Window, Cancellable, AsyncReadyCallback).

      Parameters:
      handler - the signal handler
      Returns:
      a signal handler ID to keep track of the signal connection
      See Also:
    • emitActivateLink

      public boolean emitActivateLink(String uri)
      Emits the "activate-link" signal. See onActivateLink(Label.ActivateLinkCallback).
    • onCopyClipboard

      Gets emitted to copy the selection to the clipboard.

      The ::copy-clipboard signal is a keybinding signal.

      The default binding for this signal is Ctrl+c.

      Parameters:
      handler - the signal handler
      Returns:
      a signal handler ID to keep track of the signal connection
      See Also:
    • emitCopyClipboard

      public void emitCopyClipboard()
      Emits the "copy-clipboard" signal. See onCopyClipboard(Label.CopyClipboardCallback).
    • onMoveCursor

      Gets emitted when the user initiates a cursor movement.

      The ::move-cursor signal is a keybinding signal. If the cursor is not visible in entry, this signal causes the viewport to be moved instead.

      Applications should not connect to it, but may emit it with GObjects#signalEmitByName if they need to control the cursor programmatically.

      The default bindings for this signal come in two variants, the variant with the Shift modifier extends the selection, the variant without the Shift modifier does not. There are too many key combinations to list them all here.

      • , , , move by individual characters/lines
      • Ctrl+, etc. move by words/paragraphs
      • Home and End move to the ends of the buffer
      Parameters:
      handler - the signal handler
      Returns:
      a signal handler ID to keep track of the signal connection
      See Also:
    • emitMoveCursor

      public void emitMoveCursor(MovementStep step, int count, boolean extendSelection)
      Emits the "move-cursor" signal. See onMoveCursor(Label.MoveCursorCallback).
    • builder

      public static Label.Builder<? extends Label.Builder> builder()
      A Label.Builder object constructs a Label with the specified properties. Use the various set...() methods to set properties, and finish construction with Label.Builder.build().
      Returns:
      the builder object