JLabel Border and Image Example

JLabel Border and Image Example

Swing Label can be set with borders and images which is not possible with AWT Label component. Alignment is also possible.

Following code explains.

JLabel

There are three labels in the above output screen, lab1, lab2 and lab3.

JLabel lab1 = new JLabel(“Ordianry Test”);

lab1 comes with simple test like our AWT Label. Pass the text to the constructor.

JLabel lab2 = new JLabel(“This is Ordianry Test but bordered”);
lab2.setBorder(BorderFactory.createTitledBorder(“Bordered Text”));

lab2 is set with a border – titled border. It is like you have set earlier with JButton.

JLabel lab3 = new JLabel(“Birds give life to Nataure”, new ImageIcon(“bird3.gif”), SwingConstants.RIGHT);

By default image comes to left and text to right but is changed in the above statement where the image comes right and the text left.

SwingConstants.RIGHT can be changed to SwingConstants.LEFT or SwingConstants.CENTER to align the text to left and center.

Leave a Reply

Your email address will not be published. Required fields are marked *