How to set the text of the JLabel to be right-justified and vertically centered in Java?

Java 8Object Oriented ProgrammingProgramming

To set the text of the label component to be right- justified and vertically centered, you need to set the alignment while creating a new label.

Set the label to be on the right -

JLabel label = new JLabel("Name", JLabel.RIGHT);

Here, we have set the size of the label as well as the color that includes foreground and background color -

label.setPreferredSize(new Dimension(170, 70));
label.setOpaque(true);
label.setBackground(Color.MAGENTA);
label.setForeground(Color.WHITE);

The following is an example to set the text of the label to be right-justified and vertically centered −

Example

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("Name", JLabel.RIGHT);
      label.setPreferredSize(new Dimension(170, 70));
      label.setOpaque(true);
      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("AMIT");
      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


raja
Published on 04-Jun-2019 09:45:40
Advertisements