Java JLabel(Icon image, int horizontalAlignment) Constructor

Syntax

JLabel(Icon image, int horizontalAlignment) constructor from JLabel has the following syntax.

public JLabel(Icon image,  int horizontalAlignment)

Example

In the following code shows how to use JLabel.JLabel(Icon image, int horizontalAlignment) constructor.


//from  w w w  .j a v  a 2  s.  c  om

import java.awt.Component;
import java.awt.Graphics;

import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main extends JPanel {

  public Main() {
    JLabel jl = new JLabel( new MyIcon(), JLabel.CENTER);

    add(jl);

  }

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.getContentPane().add(new Main());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(200, 200);
    frame.setVisible(true);
  }

}

class MyIcon implements Icon {
  public int getIconWidth() {
    return 32;
  }

  public int getIconHeight() {
    return 32;
  }

  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.drawString("java2s.com", 0, 20);
  }
}