Can we create nested TitiledBorder in Java?

Java 8Object Oriented ProgrammingProgramming

Yes, we can create nested TitledBorder. Let us first create a component for which we will set the border −

JLabel label = new JLabel();

Now, we will create the 1st border −

TitledBorder border = BorderFactory.createTitledBorder("Top Border");
border.setTitlePosition(TitledBorder.TOP);

Following is how we will creater border 2. We have set the 1st border here −

TitledBorder border2 = new TitledBorder(border, "Bottom CENTER Border",TitledBorder.CENTER,TitledBorder.BOTTOM);

Now, set it for the label component −

label.setBorder(border2);

The following is an example to create nested TitledBorder in Java −

package my;
import java.awt.BorderLayout;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
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);
      TitledBorder border = BorderFactory.createTitledBorder("Top Border");
      border.setTitlePosition(TitledBorder.TOP);
      TitledBorder border2 = new TitledBorder(border, "Bottom CENTER Border", TitledBorder.CENTER, TitledBorder.BOTTOM);
      JLabel label = new JLabel();
      label.setBorder(border2);
      Container contentPane = frame.getContentPane();
      contentPane.add(label, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}

Output

raja
Published on 06-Jun-2019 09:58:13
Advertisements