This is a Java program to display some text in the frame with the help of a label.
We have to write a program in Java such that it displays some text in a frame using JLabel.
To display text using a label, we have the following set of input and output.
To display a text:
At the execution of the program, it is expected that a frame appears with some text written with the help of a label.
Text is “This text is written using a label”
1. Create a frame and a label.
2. Add the label to the frame.
3. Write some text to the label.
4. Display the frame.
Here is source code of the Java Program to display text in a frame using a label. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.
/*Java Program to display text using label*/
import javax.swing.*;
import java.awt.*;
class Text_Label
{
//Driver function
public static void main(String args[])
{
//Create a frame
JFrame frame=new JFrame("Text using Label");
frame.setSize(500,500);
frame.setBackground(Color.white);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(null);
//Create a Label
JLabel label=new JLabel();
label.setBounds(0,100,500,50);
frame.add(label);
//Write text to the label
String str="This text is written using a label";
label.setText(str);
//Display the frame
frame.setVisible(true);
}
}
1. Create a frame with background color & specific size. frame.setBackground(Color.white); is used to create the frame background color as white. frame.setSize(500,500); is used to set the width and height of the frame.
2. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); is a default close operation for the frame.
3. Create a label with a setBounds() values and add it to the frame by using frame.add();.
JLabel label=new JLabel(); –> Used to create the label.
label.setBounds(0,100,500,50); –> Sets the position of label.
frame.add(label); –> It will add the label to the frame.
4. String str=”This text is written using a label”; –> It is used to write text to the label. Text is “This text is written using a label”
5. label.setText(str); –> It will add the text to the label.
6. frame.setVisible(true); is used to display the frame. The frame will display with the text “This text is written using a label” which is added to the label.
Here’s the run time test case for displaying text in a frame using a label.
Test case – Here’s the runtime output to display a text. Once the program is executed, it displays the frame with text “This text is written using a label”.
Sanfoundry Global Education & Learning Series – Java Programs.
- Check Programming Books
- Apply for Java Internship
- Practice Information Technology MCQs
- Check Java Books
- Practice BCA MCQs