Class Label
- All Implemented Interfaces:
Accessible,AccessibleText,Buildable,ConstraintTarget,Proxy
Most labels are used to label another widget (such as an Entry).
Shortcuts and Gestures
GtkLabel supports the following keyboard shortcuts, when the cursor is
visible:
Shift+F10orMenuopens the context menu.Ctrl+AorCtrl+/selects all.Ctrl+Shift+AorCtrl+\unselects all.
Additionally, the following signals have default keybindings:
Gtk.Label::activate-current-linkGtk.Label::copy-clipboardGtk.Label::move-cursor
Actions
GtkLabel defines a set of built-in actions:
clipboard.copycopies the text to the clipboard.clipboard.cutdoesn't do anything, since text in labels can't be deleted.clipboard.pastedoesn't do anything, since text in labels can't be edited.link.openopens the link, when activated on a link inside the label.link.copycopies the link to the clipboard, when activated on a link inside the label.menu.popupopens the context menu.selection.deletedoesn't do anything, since text in labels can't be deleted.selection.select-allselects 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(java.lang.String) or
setTextWithMnemonic(java.lang.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(org.gnome.gtk.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(org.gnome.gtk.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(java.lang.String, int, int, org.javagi.base.Out<org.gnome.pango.AttrList>, org.javagi.base.Out<java.lang.String>, org.javagi.base.Out<java.lang.Integer>))
The markup passed to setMarkup(java.lang.String) must be valid XML; for example,
literal <, > and & characters must be escaped as <, >, and &.
If you pass text obtained from the user, file, or a network to
setMarkup(java.lang.String), you’ll want to escape it with
GLib.markupEscapeText(java.lang.String, long) or GLib.markupPrintfEscaped(java.lang.String, java.lang.Object...).
Markup strings are just a convenient way to set the Pango.AttrList
on a label; setAttributes(org.gnome.pango.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 [0, G_MAXINT)). The reason is that specifying the start_index and
end_index for a 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(org.gnome.gtk.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.
Links
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=\\"<i>Our</i> 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.
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic interfaceFunctional interface declaration of theActivateCurrentLinkCallbackcallback.static interfaceFunctional interface declaration of theActivateLinkCallbackcallback.static classLabel.Builder<B extends Label.Builder<B>>Inner class implementing a builder pattern to construct a GObject with properties.static interfaceFunctional interface declaration of theCopyClipboardCallbackcallback.static interfaceFunctional interface declaration of theMoveCursorCallbackcallback.Nested classes/interfaces inherited from class org.gnome.gtk.Widget
Widget.DestroyCallback, Widget.DirectionChangedCallback, Widget.HideCallback, Widget.KeynavFailedCallback, Widget.MapCallback, Widget.MnemonicActivateCallback, Widget.MoveFocusCallback, Widget.QueryTooltipCallback, Widget.RealizeCallback, Widget.ShowCallback, Widget.StateFlagsChangedCallback, Widget.UnmapCallback, Widget.UnrealizeCallback, Widget.Widget$Impl, Widget.WidgetClassNested classes/interfaces inherited from class org.gnome.gobject.InitiallyUnowned
InitiallyUnowned.InitiallyUnownedClassNested classes/interfaces inherited from class org.gnome.gobject.GObject
GObject.NotifyCallback, GObject.ObjectClassNested classes/interfaces inherited from interface org.gnome.gtk.Accessible
Accessible.Accessible$Impl, Accessible.AccessibleInterfaceNested classes/interfaces inherited from interface org.gnome.gtk.AccessibleText
AccessibleText.AccessibleText$Impl, AccessibleText.AccessibleTextInterfaceNested classes/interfaces inherited from interface org.gnome.gtk.Buildable
Buildable.Buildable$Impl, Buildable.BuildableIfaceNested classes/interfaces inherited from interface org.gnome.gtk.ConstraintTarget
ConstraintTarget.ConstraintTarget$Impl, ConstraintTarget.ConstraintTargetInterface -
Constructor Summary
ConstructorsConstructorDescriptionLabel()Creates a new Label.Creates a new label with the given text inside it.Label(MemorySegment address) Create a Label proxy instance for the provided memory address. -
Method Summary
Modifier and TypeMethodDescriptionprotected LabelasParent()Returns this instance as if it were its parent type.static Label.Builder<? extends Label.Builder> builder()ALabel.Builderobject constructs aLabelwith the specified properties.voidEmits the "activate-current-link" signal.booleanemitActivateLink(String uri) Emits the "activate-link" signal.voidEmits the "copy-clipboard" signal.voidemitMoveCursor(MovementStep step, int count, boolean extendSelection) Emits the "move-cursor" signal.@Nullable AttrListGets the label's attribute list.@Nullable StringReturns the URI for the active link in the label.Returns the ellipsization mode of the label.@Nullable MenuModelGets the extra menu model of the label.Returns the justification of the label.getLabel()Fetches the text from a label.Gets the Pango layout used to display the label.voidgetLayoutOffsets(@Nullable Out<Integer> x, @Nullable Out<Integer> y) Obtains the coordinates where the label will draw its Pango layout.intgetLines()Gets the number of lines to which an ellipsized, wrapping label should be limited.intRetrieves the maximum width of the label in characters.intReturn the mnemonic accelerator.@Nullable WidgetRetrieves the mnemonic target of this label.Returns natural line wrap mode used by the label.booleanReturns whether the label is selectable.booleangetSelectionBounds(@Nullable Out<Integer> start, @Nullable Out<Integer> end) Gets the selected range of characters in the label.booleanReturns whether the label is in single line mode.@Nullable TabArraygetTabs()Gets the tab stops for the label.getText()Gets the text of the label.static @Nullable TypegetType()Get the GType of the Label classbooleanReturns whether the label’s text is interpreted as Pango markup.booleanReturns whether underlines in the label indicate mnemonics.intRetrieves the desired width of the label in characters.booleangetWrap()Returns whether lines in the label are automatically wrapped.Returns line wrap mode used by the label.floatGets thexalignof the label.floatGets theyalignof the label.Gets emitted when the user activates a link in the label.onActivateLink(Label.ActivateLinkCallback handler) Gets emitted to activate a URI.Gets emitted to copy the selection to the clipboard.onMoveCursor(Label.MoveCursorCallback handler) Gets emitted when the user initiates a cursor movement.voidselectRegion(int startOffset, int endOffset) Selects a range of characters in the label, if the label is selectable.voidsetAttributes(@Nullable AttrList attrs) Apply attributes to the label text.voidsetEllipsize(EllipsizeMode mode) Sets the mode used to ellipsize the text.voidsetExtraMenu(@Nullable MenuModel model) Sets a menu model to add to the context menu of the label.voidsetJustify(Justification jtype) Sets the alignment of lines in the label relative to each other.voidSets the text of the label.voidsetLines(int lines) Sets the number of lines to which an ellipsized, wrapping label should be limited.voidSets the labels text and attributes from markup.voidSets the labels text, attributes and mnemonic from markup.voidsetMaxWidthChars(int nChars) Sets the maximum width of the label in characters.voidsetMnemonicWidget(@Nullable Widget widget) Associate the label with its mnemonic target.voidsetNaturalWrapMode(NaturalWrapMode wrapMode) Selects the line wrapping for the natural size request.voidsetSelectable(boolean setting) Makes text in the label selectable.voidsetSingleLineMode(boolean singleLineMode) Sets whether the label is in single line mode.voidSets tab stops for the label.voidSets the text for the label.voidSets the text for the label, with mnemonics.voidsetUseMarkup(boolean setting) Sets whether the text of the label contains markup.voidsetUseUnderline(boolean setting) Sets whether underlines in the text indicate mnemonics.voidsetWidthChars(int nChars) Sets the desired width in characters of the label.voidsetWrap(boolean wrap) Toggles line wrapping within the label.voidsetWrapMode(WrapMode wrapMode) Controls how line wrapping is done.voidsetXalign(float xalign) Sets thexalignof the label.voidsetYalign(float yalign) Sets theyalignof the label.static LabelwithMnemonic(@Nullable String str) Creates a new label with the given text inside it, and a mnemonic.Methods inherited from class org.gnome.gtk.Widget
actionSetEnabled, activateActionIfExists, activateDefault, activateWidget, addController, addCssClass, addMnemonicLabel, addTickCallback, allocate, childFocus, computeBounds, computeExpand, computeExpand, computePoint, computeTransform, contains, createPangoContext, createPangoLayout, cssChanged, directionChanged, disposeTemplate, dragCheckThreshold, emitDestroy, emitDirectionChanged, emitHide, emitKeynavFailed, emitMap, emitMnemonicActivate, emitMoveFocus, emitQueryTooltip, emitRealize, emitShow, emitStateFlagsChanged, emitUnmap, emitUnrealize, errorBell, focus, getAllocatedBaseline, getAllocatedHeight, getAllocatedWidth, getAllocation, getAncestor, getBaseline, getCanFocus, getCanTarget, getChildVisible, getClipboard, getColor, getCssClasses, getCssName, getCursor, getDefaultDirection, getDirection, getDisplay, getFirstChild, getFocusable, getFocusChild, getFocusOnClick, getFontMap, getFontOptions, getFrameClock, getHalign, getHasTooltip, getHeight, getHexpand, getHexpandSet, getLastChild, getLayoutManager, getLimitEvents, getMapped, getMarginBottom, getMarginEnd, getMarginStart, getMarginTop, getMemoryLayout, getName, getNative, getNextSibling, getOpacity, getOverflow, getPangoContext, getParent, getPreferredSize, getPrevSibling, getPrimaryClipboard, getRealized, getReceivesDefault, getRequestMode, getRoot, getScaleFactor, getSensitive, getSettings, getSize, getSizeRequest, getStateFlags, getStyleContext, getTemplateChild, getTooltipMarkup, getTooltipText, getValign, getVexpand, getVexpandSet, getVisible, getWidth, grabFocus, hasCssClass, hasDefault, hasFocus, hasVisibleFocus, hide, inDestruction, initTemplate, insertActionGroup, insertAfter, insertBefore, isAncestor, isDrawable, isFocus, isSensitive, isVisible, keynavFailed, listMnemonicLabels, map, measure, mnemonicActivate, moveFocus, observeChildren, observeControllers, onDestroy, onDirectionChanged, onHide, onKeynavFailed, onMap, onMnemonicActivate, onMoveFocus, onQueryTooltip, onRealize, onShow, onStateFlagsChanged, onUnmap, onUnrealize, pick, pick, queryTooltip, queueAllocate, queueDraw, queueResize, realize, removeController, removeCssClass, removeMnemonicLabel, removeTickCallback, root, setCanFocus, setCanTarget, setChildVisible, setCssClasses, setCursor, setCursorFromName, setDefaultDirection, setDirection, setFocusable, setFocusChild, setFocusOnClick, setFontMap, setFontOptions, setHalign, setHasTooltip, setHexpand, setHexpandSet, setLayoutManager, setLimitEvents, setMarginBottom, setMarginEnd, setMarginStart, setMarginTop, setName, setOpacity, setOverflow, setParent, setReceivesDefault, setSensitive, setSizeRequest, setStateFlags, setStateFlags, setTooltipMarkup, setTooltipText, setValign, setVexpand, setVexpandSet, setVisible, shouldLayout, show, sizeAllocate, sizeAllocate, snapshot, snapshotChild, stateFlagsChanged, systemSettingChanged, translateCoordinates, triggerTooltipQuery, unmap, unparent, unrealize, unroot, unsetStateFlags, unsetStateFlagsMethods inherited from class org.gnome.gobject.GObject
addToggleRef, addWeakPointer, bindProperty, bindProperty, bindProperty, bindPropertyFull, bindPropertyFull, bindPropertyWithClosures, bindPropertyWithClosures, compatControl, connect, connect, connect, constructed, disconnect, dispatchPropertiesChanged, dispose, dupData, dupQdata, emit, emitNotify, finalize_, forceFloating, freezeNotify, get, getData, getProperty, getProperty, getProperty, getQdata, getv, interfaceFindProperty, interfaceInstallProperty, interfaceListProperties, isFloating, newInstance, newInstance, newv, notify, notify, notifyByPspec, onNotify, ref, refSink, removeToggleRef, removeWeakPointer, replaceData, replaceQdata, runDispose, set, setData, setDataFull, setProperty, setProperty, setProperty, setQdata, setQdataFull, setv, stealData, stealQdata, takeRef, thawNotify, unref, watchClosure, weakRef, weakUnref, withPropertiesMethods inherited from class org.gnome.gobject.TypeInstance
callParent, callParent, cast, getPrivate, readGClass, writeGClassMethods inherited from class org.javagi.base.ProxyInstance
equals, handle, hashCodeMethods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.gnome.gtk.Accessible
announce, getAccessibleParent, getAccessibleRole, getAtContext, getBounds, getFirstAccessibleChild, getNextAccessibleSibling, getPlatformState, resetProperty, resetRelation, resetState, setAccessibleParent, updateNextAccessibleSibling, updatePlatformState, updateProperty, updateRelation, updateStateMethods inherited from interface org.gnome.gtk.AccessibleText
updateCaretPosition, updateContents, updateSelectionBoundMethods inherited from interface org.gnome.gtk.Buildable
getBuildableId
-
Constructor Details
-
Label
Create a Label proxy instance for the provided memory address.- Parameters:
address- the memory address of the native object
-
Label
Creates a new label with the given text inside it.You can pass
NULLto get an empty label widget.- Parameters:
str- the text of the label
-
Label
public Label()Creates a new Label.
-
-
Method Details
-
getType
-
asParent
Returns this instance as if it were its parent type. This is mostly synonymous to the Javasuperkeyword, but will set the native typeclass function pointers to the parent type. When overriding a native virtual method in Java, "chaining up" withsuper.methodName()doesn't work, because it invokes the overridden function pointer again. To chain up, callasParent().methodName(). This will call the native function pointer of this virtual method in the typeclass of the parent type. -
withMnemonic
Creates a new label with the given text inside it, and a mnemonic.If characters in
strare 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 usingsetMnemonicWidget(org.gnome.gtk.Widget).If
setMnemonicWidget(org.gnome.gtk.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
Gets the label's attribute list.This is the
Pango.AttrListthat was set on the label usingsetAttributes(org.gnome.pango.AttrList), if any. This function does not reflect attributes that come from the label's markup (seesetMarkup(java.lang.String)). If you want to get the effective attributes for the label, usepango_layout_get_attributes (gtk_label_get_layout (self)).- Returns:
- the attribute list
-
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-linkhandler or for use in aGtk.Widget::query-tooltiphandler.- Returns:
- the active URI
-
getEllipsize
Returns the ellipsization mode of the label.- Returns:
- the ellipsization mode
-
getExtraMenu
Gets the extra menu model of the label.- Returns:
- the menu model
-
getJustify
Returns the justification of the label.- Returns:
- the justification value
-
getLabel
-
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(org.javagi.base.Out<java.lang.Integer>, org.javagi.base.Out<java.lang.Integer>). The returned layout is owned by thelabelso need not be freed by the caller. Thelabelis free to recreate its layout at any time, so it should be considered read-only.- Returns:
- the
Layoutfor this label
-
getLayoutOffsets
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 theLayoutfunctions you need to convert to and from pixels usingPANGO_PIXELS()orPango.SCALE.- Parameters:
x- location to store X offset of layouty- 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
Retrieves the mnemonic target of this label.- Returns:
- the target of the label’s mnemonic,
or
NULLif none has been set and the default algorithm will be used.
-
getNaturalWrapMode
Returns natural line wrap mode used by the label.- 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
Gets the selected range of characters in the label.The returned
startandendpositions are in characters.- Parameters:
start- return location for start of selectionend- 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
Gets the tab stops for the label.The returned array will be
NULLif “standard” (8-space) tabs are used.- Returns:
- copy of default tab array,
or
NULLif standard tabs are used - Since:
- 4.8
-
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.- Returns:
- true if the label’s text will be parsed for markup
-
getUseUnderline
public boolean getUseUnderline()Returns whether underlines in the label indicate mnemonics.- 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
Returns line wrap mode used by the label.- Returns:
- the line wrap mode
-
getXalign
public float getXalign()Gets thexalignof the label.See the
Gtk.Label:xalignproperty.- Returns:
- the xalign value
-
getYalign
public float getYalign()Gets theyalignof the label.See the
Gtk.Label:yalignproperty.- 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. IfstartOffsetorendOffsetare -1, then the end of the label will be substituted.- Parameters:
startOffset- start offset, in charactersendOffset- end offset, in characters
-
setAttributes
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-underlineorGtk.Label:use-markuppropertiesWhile 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
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
Sets a menu model to add to the context menu of the label.- Parameters:
model- a menu model
-
setJustify
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.leftis the default value when the widget is first created withLabel().If you instead want to set the alignment of the label as a whole, use
Widget.setHalign(org.gnome.gtk.Align)instead.- Parameters:
jtype- the new justification
-
setLabel
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-underlineandGtk.Label:use-markupproperties.- 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
Sets the labels text and attributes from markup.The string must be marked up with Pango markup (see
Pango.parseMarkup(java.lang.String, int, int, org.javagi.base.Out<org.gnome.pango.AttrList>, org.javagi.base.Out<java.lang.String>, org.javagi.base.Out<java.lang.Integer>)).If
stris external data, you may need to escape it withGLib.markupEscapeText(java.lang.String, long)orGLib.markupPrintfEscaped(java.lang.String, java.lang.Object...):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-markupproperty to true.Also see
setText(java.lang.String).- Parameters:
str- the markup string
-
setMarkupWithMnemonic
Sets the labels text, attributes and mnemonic from markup.Parses
strwhich is marked up with Pango markup (seePango.parseMarkup(java.lang.String, int, int, org.javagi.base.Out<org.gnome.pango.AttrList>, org.javagi.base.Out<java.lang.String>, org.javagi.base.Out<java.lang.Integer>)), setting the label’s text and attribute list based on the parse results. If characters instrare 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(org.gnome.gtk.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
Associate the label with its mnemonic target.If the label has been set so that it has a mnemonic key (using i.e.
setMarkupWithMnemonic(java.lang.String),setTextWithMnemonic(java.lang.String),withMnemonic(java.lang.String)or theGtk.Label:use_underlineproperty) the label can be associated with a widget that is the target of the mnemonic. When the label is inside a widget (like aButtonor aNotebooktab) it is automatically associated with the correct widget, but sometimes (i.e. when the target is aEntrynext to the label) you need to set it explicitly using this function.The target widget will be accelerated by emitting the
Gtk.Widget::mnemonic-activatesignal 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
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-modeproperty.- 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
Sets tab stops for the label.- Parameters:
tabs- tab stops- Since:
- 4.8
-
setText
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-underlineandGtk.Label:use-markupproperties to false.Also see
setMarkup(java.lang.String).- Parameters:
str- the text to show in this Label
-
setTextWithMnemonic
Sets the text for the label, with mnemonics.If characters in
strare 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 usingsetMnemonicWidget(org.gnome.gtk.Widget).- Parameters:
str- the text
-
setUseMarkup
public void setUseMarkup(boolean setting) Sets whether the text of the label contains markup.- 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
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-modeproperty.- Parameters:
wrapMode- the line wrapping mode
-
setXalign
public void setXalign(float xalign) Sets thexalignof the label.See the
Gtk.Label:xalignproperty.- Parameters:
xalign- the new xalign value, between 0 and 1
-
setYalign
public void setYalign(float yalign) Sets theyalignof the label.See the
Gtk.Label:yalignproperty.- Parameters:
yalign- the new yalign value, between 0 and 1
-
onActivateCurrentLink
public SignalConnection<Label.ActivateCurrentLinkCallback> onActivateCurrentLink(Label.ActivateCurrentLinkCallback handler) Gets emitted when the user activates a link in the label.The
::activate-current-linkis 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
Enterkey.- 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. SeeonActivateCurrentLink(org.gnome.gtk.Label.ActivateCurrentLinkCallback). -
onActivateLink
public SignalConnection<Label.ActivateLinkCallback> onActivateLink(Label.ActivateLinkCallback handler) Gets emitted to activate a URI.Applications may connect to it to override the default behaviour, which is to call
FileLauncher.launch(org.gnome.gtk.Window, org.gnome.gio.Cancellable, org.gnome.gio.AsyncReadyCallback).- Parameters:
handler- the signal handler- Returns:
- a signal handler ID to keep track of the signal connection
- See Also:
-
emitActivateLink
Emits the "activate-link" signal. SeeonActivateLink(org.gnome.gtk.Label.ActivateLinkCallback). -
onCopyClipboard
public SignalConnection<Label.CopyClipboardCallback> onCopyClipboard(Label.CopyClipboardCallback handler) Gets emitted to copy the selection to the clipboard.The
::copy-clipboardsignal 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. SeeonCopyClipboard(org.gnome.gtk.Label.CopyClipboardCallback). -
onMoveCursor
Gets emitted when the user initiates a cursor movement.The
::move-cursorsignal is a keybinding signal. If the cursor is not visible inentry,this signal causes the viewport to be moved instead.Applications should not connect to it, but may emit it with
GObjects.signalEmitByName(org.gnome.gobject.GObject, java.lang.String, java.lang.Object...)if they need to control the cursor programmatically.The default bindings for this signal come in two variants, the variant with the
Shiftmodifier extends the selection, the variant without theShiftmodifier does not. There are too many key combinations to list them all here.←,→,↑,↓move by individual characters/linesCtrl+←, etc. move by words/paragraphsHomeandEndmove 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
Emits the "move-cursor" signal. SeeonMoveCursor(org.gnome.gtk.Label.MoveCursorCallback). -
builder
ALabel.Builderobject constructs aLabelwith the specified properties. Use the variousset...()methods to set properties, and finish construction withLabel.Builder.build().- Returns:
- the builder object
-