Advertisement



< Prev
Next >



Label class





Label class is used to create a label, which can be used to display a text information to the user or a text before the textfield or an image. Label is a component which extends JComponent class and it is added to the container like Frame or a component like Panel.




Constructors of Label


Constructor Description
public Label() Creates a Label with an empty text.
public Label(String text) Creates a Label with an specified text.
public Label(String text, int alignment) Creates a Label with an specified text and alignment.


Label's alignment could be any of these fields -




Methods of Label class


Methods Description
public void setText(String text) Sets a String message on the Label.
public String getText() Gets a String message of Label.
void setAlignment(int alignment) Sets an alignment on this label.
void int getAlignment() Gets the current alignment of this label





An example of Label


import javax.swing.*;
import java.awt.*;

public class LabelEx1
{
Frame jf;
Label label1, label2, label3;

LabelEx1()
{
jf = new Frame("Label example");

label1 = new Label("Hi!");
label2 = new Label("Bonjour, how are you?");
label3 = new Label("We wish you pleasant day ahead, Take care!");


label1.setText("Welcome and Hello!"); 	//Setting the text of a JLabal
jf.setLayout(new FlowLayout());
jf.add(label1);			//Adding label1 to the Jframe
jf.add(label2);			//Adding label2 to the Jframe
jf.add(label3);			//Adding label3 to the Jframe
jf.setVisible(true);
jf.setSize(300,300);
}

public static void main(String... ar)
{
new LabelEx1();
}

}

When you run the code, you are presented a window shown below -:

Figure 1



Advertisement




Setting the alignment of Label


import javax.swing.*;
import java.awt.*;

public class LabelEx2
{
Frame jf;
Label label1, label2, label3;

LabelEx2()
{
jf = new Frame("Label example");

label1 = new Label("NORTHEAST", Label.RIGHT);
label2 = new Label("SOUTHWEST", Label.LEFT);
label3 = new Label("CENTRAL", Label.CENTER);

//("Hello!"); 	//Setting the text of a JLabal
jf.add(label1, BorderLayout.NORTH);			//Adding label1 to the Jframe
jf.add(label2, BorderLayout.SOUTH);			//Adding label2 to the Jframe
jf.add(label3, BorderLayout.CENTER);			//Adding label3 to the Jframe
jf.setVisible(true);
jf.setSize(300,300);
}

public static void main(String... ar)
{
new LabelEx2();
}

}
When you run the code, you are presented a window shown in the Figure2 below -:

Figure 2




Please share this article -





< Prev
Next >
< Dialog Boxes
TextField >



Advertisement

Please Subscribe

Please subscribe to our social media channels for daily updates.


Decodejava Facebook Page  DecodeJava Twitter Page Decodejava Google+ Page




Advertisement

Notifications



Please check our latest addition

PYTHON and DJANGO


Advertisement