Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set the content of the JLabel to be left-justified and top-aligned in Java
To set the text of the label component to be left-justified and top-aligned, you need to set the alignment. Set the label to be on the left and top aligned ?
JLabel label = new JLabel("Department");
label.setVerticalAlignment(JLabel.TOP);
Here, we have set the size of the label as well as the color that includes foreground and background color ?
label.setPreferredSize(new Dimension(220, 70)); label.setOpaque(true); label.setBackground(Color.MAGENTA); label.setForeground(Color.WHITE);
In Java, when we talk about setting the content of a JLabel to be left-justified and top-aligned, we are referring to how the text or icon within the label is positioned relative to the label's boundaries.
Left-Justified: The content starts at the left edge of the label.
Top-Aligned: The content starts at the top edge of the label.
Example to set content of label to be left and top-aligned
The following is an example to set the content of the label to be left-justified and top-aligned ?
Example
In this program, we create a simple GUI window with a JLabel and a JTextArea using Swing. The JLabel is customized with specific size, color, font, and top alignment, while the JTextArea is set with text and font. The components are added to a JFrame which results in the output.
package my;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
public class SwingDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Frame");
frame.setLayout(new FlowLayout());
JLabel label = new JLabel("Department");
label.setPreferredSize(new Dimension(220, 70));
label.setOpaque(true);
label.setVerticalAlignment(JLabel.TOP);
label.setBackground(Color.MAGENTA);
label.setForeground(Color.WHITE);
Font font = new Font("Serif", Font.BOLD, 18);
label.setFont(font);
JTextArea text = new JTextArea();
text.setText("Operations");
font = new Font("Serif", Font.BOLD, 14);
text.setFont(font);
frame.add(label);
frame.add(text);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(500, 300);
frame.setVisible(true);
}
}
Output
The above program produce the following result ?
