Use labels in java

Class JLabel

A display area for a short text string or an image, or both. A label does not react to input events. As a result, it cannot get the keyboard focus. A label can, however, display a keyboard alternative as a convenience for a nearby component that has a keyboard alternative but can’t display it.

A JLabel object can display either text, an image, or both. You can specify where in the label’s display area the label’s contents are aligned by setting the vertical and horizontal alignment. By default, labels are vertically centered in their display area. Text-only labels are leading edge aligned, by default; image-only labels are horizontally centered, by default.

You can also specify the position of the text relative to the image. By default, text is on the trailing edge of the image, with the text and image vertically aligned.

A label’s leading and trailing edge are determined from the value of its ComponentOrientation property. At present, the default ComponentOrientation setting maps the leading edge to left and the trailing edge to right.

Finally, you can use the setIconTextGap method to specify how many pixels should appear between the text and the image. The default is 4 pixels.

Читайте также:  Python test module load

See How to Use Labels in The Java Tutorial for further documentation.

Warning: Swing is not thread safe. For more information see Swing’s Threading Policy.

Warning: Serialized objects of this class will not be compatible with future Swing releases. The current serialization support is appropriate for short term storage or RMI between applications running the same version of Swing. As of 1.4, support for long term storage of all JavaBeans has been added to the java.beans package. Please see XMLEncoder .

Источник

Class Label

A Label object is a component for placing text in a container. A label displays a single line of read-only text. The text can be changed by the application, but a user cannot edit it directly.

setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10)); add(new Label("Hi There!")); add(new Label("Another Label"));

produces the following labels:

Nested Class Summary

Nested classes/interfaces declared in class java.awt.Component

Field Summary

Fields declared in class java.awt.Component

Fields declared in interface java.awt.image.ImageObserver

Constructor Summary

Method Summary

Methods declared in class java.awt.Component

Methods declared in class java.lang.Object

Field Details

LEFT

CENTER

Constructor Details

Label

Label

Label

Constructs a new label that presents the specified string of text with the specified alignment. Possible values for alignment are Label.LEFT , Label.RIGHT , and Label.CENTER .

Method Details

addNotify

Creates the peer for this label. The peer allows us to modify the appearance of the label without changing its functionality.

getAlignment

Gets the current alignment of this label. Possible values are Label.LEFT , Label.RIGHT , and Label.CENTER .

setAlignment

Sets the alignment for this label to the specified alignment. Possible values are Label.LEFT , Label.RIGHT , and Label.CENTER .

getText

setText

paramString

Returns a string representing the state of this Label . This method is intended to be used only for debugging purposes, and the content and format of the returned string may vary between implementations. The returned string may be empty but may not be null .

getAccessibleContext

Gets the AccessibleContext associated with this Label. For labels, the AccessibleContext takes the form of an AccessibleAWTLabel. A new AccessibleAWTLabel instance is created if necessary.

Report a bug or suggest an enhancement
For further API reference and developer documentation see the Java SE Documentation, which contains more detailed, developer-targeted descriptions with conceptual overviews, definitions of terms, workarounds, and working code examples. Other versions.
Java is a trademark or registered trademark of Oracle and/or its affiliates in the US and other countries.
Copyright © 1993, 2023, Oracle and/or its affiliates, 500 Oracle Parkway, Redwood Shores, CA 94065 USA.
All rights reserved. Use is subject to license terms and the documentation redistribution policy.

Источник

How to Use Labels

With the JLabel class, you can display unselectable text and images. If you need to create a component that displays a string, an image, or both, you can do so by using or extending JLabel . If the component is interactive and has a certain state, use a button instead of a label.

By specifying HTML code in a label’s text, you can give the label various characteristics such as multiple lines, multiple fonts or multiple colors. If the label uses just a single color or font, you can avoid the overhead of HTML processing by using the setForeground or setFont method instead. See Using HTML in Swing Components for details.

Note that labels are not opaque by default. If you need to paint the label’s background, it is recommended that you turn its opacity property to «true». The following code snippet shows how to do this.

The following picture introduces an application that displays three labels. The window is divided into three rows of equal height; the label in each row is as wide as possible.

A snapshot of LabelDemo, which uses labels with text and icons.

Try this:

  1. Click the Launch button to run the Label Demo using Java™ Web Start (download JDK 7 or later). Alternatively, to compile and run the example yourself, consult the example index.
  2. Resize the window so you can see how the labels’ contents are placed within the labels’ drawing area.
    All the label contents have default vertical alignment — that is, the label contents are centered vertically in the label’s drawing area. The top label, which contains both an image and text, has horizontal center alignment. The second label, which contains just text, has left (leading) alignment, which is the default for text-only labels in left-to-right languages. The third label, which contains just an image, has horizontal center alignment, which is the default for image-only labels.

Below is the code from LabelDemo.java that creates the labels in the previous example.

ImageIcon icon = createImageIcon("images/middle.gif"); . . . label1 = new JLabel("Image and Text", icon, JLabel.CENTER); //Set the position of the text, relative to the icon: label1.setVerticalTextPosition(JLabel.BOTTOM); label1.setHorizontalTextPosition(JLabel.CENTER); label2 = new JLabel("Text-Only Label"); label3 = new JLabel(icon);

The code for the createImageIcon method is similar to that used throughout this tutorial. You can find it in How to Use Icons.

Often, a label describes another component. When this occurs, you can improve your program’s accessibility by using the setLabelFor method to identify the component that the label describes. For example:

amountLabel.setLabelFor(amountField);

The preceding code, taken from the FormattedTextFieldDemo example discussed in How to Use Formatted Text Fields, lets assistive technologies know that the label ( amountLabel ) provides information about the formatted text field ( amountField ). For more information about assistive technologies, see How to Support Assistive Technologies.

The Label API

The following tables list the commonly used JLabel constructors and methods. Other methods you are likely to call are defined by the Component and JComponent classes. They include setFont , setForeground , setBorder , setOpaque , and setBackground . See The JComponent Class for details. The API for using labels falls into three categories:

In the following API, do not confuse label alignment with X and Y alignment. X and Y alignment are used by layout managers and can affect the way any component — not just a label — is sized or positioned. Label alignment, on the other hand, has no effect on a label’s size or position. Label alignment simply determines where, inside the label’s painting area, the label’s contents are positioned. Typically, the label’s painting area is exactly the size needed to paint on the label and thus label alignment is irrelevant. For more information about X and Y alignment, see How to Use BoxLayout.

Setting or Getting the Label’s Contents
Method or Constructor Purpose
JLabel(Icon)
JLabel(Icon, int)
JLabel(String)
JLabel(String, Icon, int)
JLabel(String, int)
JLabel()
Creates a JLabel instance, initializing it to have the specified text/image/alignment. The int argument specifies the horizontal alignment of the label’s contents within its drawing area. The horizontal alignment must be one of the following constants defined in the SwingConstants interface (which JLabel implements): LEFT , CENTER , RIGHT , LEADING , or TRAILING . For ease of localization, we strongly recommend using LEADING and TRAILING , rather than LEFT and RIGHT .
void setText(String)
String getText()
Sets or gets the text displayed by the label. You can use HTML tags to format the text, as described in Using HTML in Swing Components.
void setIcon(Icon)
Icon getIcon()
Sets or gets the image displayed by the label.
void setDisplayedMnemonic(char)
char getDisplayedMnemonic()
Sets or gets the letter that should look like a keyboard alternative. This is helpful when a label describes a component (such as a text field) that has a keyboard alternative but cannot display it. If the labelFor property is also set (using setLabelFor ), then when the user activates the mnemonic, the keyboard focus is transferred to the component specified by the labelFor property.
void setDisplayedMnemonicIndex(int)
int getDisplayedMnemonicIndex()
Sets or gets a hint as to which character in the text should be decorated to represent the mnemonic. This is useful when you have two instances of the same character and wish to decorate the second instance. For example, setDisplayedMnemonicIndex(5) decorates the character that is at position 5 (that is, the 6th character in the text). Not all types of look and feel may support this feature.
void setDisabledIcon(Icon)
Icon getDisabledIcon()
Sets or gets the image displayed by the label when it is disabled. If you do not specify a disabled image, then the look and feel creates one by manipulating the default image.
Fine Tuning the Label’s Appearance
Method Purpose
void setHorizontalAlignment(int)
void setVerticalAlignment(int)
int getHorizontalAlignment()
int getVerticalAlignment()
Sets or gets the area on the label where its contents should be placed. The SwingConstants interface defines five possible values for horizontal alignment: LEFT , CENTER (the default for image-only labels), RIGHT , LEADING (the default for text-only labels), TRAILING . For vertical alignment: TOP , CENTER (the default), and BOTTOM .
void setHorizontalTextPosition(int)
void setVerticalTextPosition(int)
int getHorizontalTextPosition()
int getVerticalTextPosition()
Sets or gets the location where the label’s text will be placed, relative to the label’s image. The SwingConstants interface defines five possible values for horizontal position: LEADING , LEFT , CENTER , RIGHT , and TRAILING (the default). For vertical position: TOP , CENTER (the default), and BOTTOM .
void setIconTextGap(int)
int getIconTextGap()
Sets or gets the number of pixels between the label’s text and its image.
Supporting Accessibility
Method Purpose
void setLabelFor(Component)
Component getLabelFor()
Sets or gets which component the label describes.

Examples That Use Labels

The following table lists some of the many examples that use labels.

Example Where Described Notes
LabelDemo This section Shows how to specify horizontal and vertical alignment as well as how to align a label’s text and image.
HtmlDemo Using HTML in Swing Components Lets you experiment with specifying HTML text for a label.
BoxAlignmentDemo Fixing Alignment Problems Demonstrates possible alignment problems when using a label in a vertical box layout. Shows how to solve the problem.
DialogDemo How to Use Dialogs Uses a changeable label to display instructions and provide feedback.
SplitPaneDemo How to Use Split Panes and How to Use Lists Displays an image using a label inside of a scroll pane.
SliderDemo2 How to Use Sliders Uses JLabel to provide labels for a slider.
TableDialogEditDemo How to Use Tables Implements a label subclass, ColorRenderer , to display colors in table cells.
FormattedTextFieldDemo How to Use Formatted Text Fields Has four rows, each containing a label and the formatted text field it describes.
TextComponentDemo Text Component Features TextComponentDemo has an inner class ( CaretListenerLabel ) that extends JLabel to provide a label that listens for events, updating itself based on the events.
ColorChooserDemo How to Use Color Choosers Uses an opaque label to display the currently chosen color against a fixed-color background.

See the Using JavaFX UI Controls: Label tutorial to learn about JavaFX labeled controls.

Источник

Оцените статью