Set the alignment of the JLabel content along the X axis on the right in Java


To set the alignment of the label’s content along the X axis on the right, use the setHorizontalAlignment() method and set the location. Let us first set a label component. We have set the label background color as well so that we can check the alignment of the label’s content properly −

JLabel label = new JLabel("Stationery");
label.setPreferredSize(new Dimension(190, 100));
label.setOpaque(true);
label.setBackground(Color.GREEN);
label.setForeground(Color.WHITE);

Now, we will align the label content along the X axis on the top by seeting location as RIGHT −

label.setHorizontalAlignment(JLabel.RIGHT);

The following is an example: to set the alignment of the label content along the X axis on the right −

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("Stationery");
      label.setPreferredSize(new Dimension(190, 100));
      label.setOpaque(true);
      label.setBackground(Color.GREEN);
      label.setForeground(Color.WHITE);
      Font font = new Font("Serif", Font.BOLD, 18);
      label.setFont(font);
      label.setHorizontalAlignment(JLabel.RIGHT);
      JTextArea text = new JTextArea();
      text.setText("Pen and Pencil");
      font = new Font("Serif", Font.BOLD, 13);
      text.setFont(font);
      frame.add(label);
      frame.add(text);
      frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      frame.setSize(500, 300);
      frame.setVisible(true);
   }
}

Output

Updated on: 30-Jul-2019

120 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements