Java Program to set alignment for text in JLabel

Java 8Object Oriented ProgrammingProgramming

JLabel Left Aligned

The following is an example to set left alignment for JLabel −

Example

import java.awt.Font;
import javax.swing.*;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Label Demo");
      JLabel label;
      label = new JLabel("Left aligned!", JLabel.LEFT);
      label.setFont(new Font("Verdana", Font.PLAIN, 13));
      frame.add(label);
      frame.setSize(500,300);
      frame.setVisible(true);
   }
}

Output

JLabel Center Aligned

The following is an example to set center alignment for JLabel −

Example

import java.awt.Font;
import javax.swing.*;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Label Demo");
      JLabel label;
      label = new JLabel("Center aligned!", JLabel.CENTER);
      label.setFont(new Font("Verdana", Font.PLAIN, 13));
      frame.add(label);
      frame.setSize(500,300);
      frame.setVisible(true);
   }
}

Output

JLabel Right Aligned

The following is an example to set right alignment for JLabel −

Example

import java.awt.Font;
import javax.swing.*;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Label Demo");
      JLabel label;
      label = new JLabel("Right aligned!", JLabel.RIGHT);
      label.setFont(new Font("Verdana", Font.PLAIN, 13));
      frame.add(label);
      frame.setSize(500,300);
      frame.setVisible(true);
   }
}

Output

raja
Published on 09-May-2019 08:49:33
Advertisements