Java JLabel set alignment

Description

Java JLabel set alignment



import java.awt.FlowLayout;
import java.awt.HeadlessException;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main extends JFrame {
  public Main() throws HeadlessException {
    setSize(150, 300);/*ww w  .  ja  va 2s  .com*/
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new FlowLayout());

    JLabel label1 = new JLabel("Username :", JLabel.RIGHT);
    JLabel label2 = new JLabel("Password :", JLabel.RIGHT);
    JLabel label3 = new JLabel("Confirm Password :", JLabel.RIGHT);
    JLabel label4 = new JLabel("Remember Me!", JLabel.LEFT);
    JLabel label5 = new JLabel("Hello.", JLabel.CENTER);

    getContentPane().add(label1);
    getContentPane().add(label2);
    getContentPane().add(label3);
    getContentPane().add(label4);
    getContentPane().add(label5);
  }

  public static void main(String[] args) {
    new Main().setVisible(true);
  }
}
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.border.Border;

public class Main {
  public static void main(String args[]) {
    JFrame f = new JFrame("Label Demo");
    f.setLayout(new FlowLayout());
    f.setSize(200, 360);//from w  w w  .  j a  va2 s.c  o  m
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    
    JLabel label= new JLabel("asdf");
    Border border = BorderFactory.createLineBorder(Color.BLACK);
    label.setBorder(border);
    label.setPreferredSize(new Dimension(150, 100));
    
    label.setText("Centered");
    label.setHorizontalAlignment(JLabel.CENTER);
    label.setVerticalAlignment(JLabel.CENTER);

    
    f.add(label);

    f.setVisible(true);
  }
}



PreviousNext

Related