How to add a title to an existing line border in Java?



Here, we will see how to add a title to an existing Line border. Let’s say we have a label and the border is to be set −

LineBorder linedBorder = new LineBorder(Color.blue); TitledBorder titledBorder = BorderFactory.createTitledBorder(linedBorder, "Demo Title"); JLabel label = new JLabel(); label.setBorder(titledBorder);

The following is an example to add a title to an existing line border −

Example

package my; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Container; import javax.swing.BorderFactory; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.border.LineBorder; import javax.swing.border.TitledBorder; public class SwingDemo {    public static void main(String args[]) {       JFrame frame = new JFrame("Demo");       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       LineBorder linedBorder = new LineBorder(Color.blue);       TitledBorder titledBorder = BorderFactory.createTitledBorder(linedBorder, "Demo Title");       JLabel label = new JLabel();       label.setBorder(titledBorder);       Container contentPane = frame.getContentPane();       contentPane.add(label, BorderLayout.CENTER);       frame.setSize(550, 300);       frame.setVisible(true);    } }

Output

Updated on: 2019-07-30T22:30:26+05:30

319 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements