Set Title Position in Java



In this article, you'll learn how to position the title of a border in a Java Swing application using the setTitlePosition() method. We'll position the title above the border's top line by utilizing the TitledBorder.ABOVE_TOP constant. This technique is useful for customizing the appearance of your Swing components.

To set title position, use the setTitlePosition() method in Java. Let's say we have to position the title above the border's top line. For that, use the constant ABOVE_TOP for the border ?

setTitlePosition(TitledBorder.ABOVE_TOP);

Steps to set title position

Following are the steps to set title position in Java ?

  • First we will import the required Java Swing classes.
  • Initialize a JFrame to serve as the main window of your application.
  • Use LineBorder for the border and TitledBorder for the title.
  • Apply the setTitlePosition() method to position the title above the top border using TitledBorder.ABOVE_TOP.
  • Add the customized border to a JLabel.
  • Set the frame size and make it visible.

Java program to set title position

The following is an example of setting title position ?

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 lineBorder = new LineBorder(Color.orange);
      TitledBorder titledBorder = BorderFactory.createTitledBorder(lineBorder, "Demo Title");
      titledBorder.setTitlePosition(TitledBorder.ABOVE_TOP);
      JLabel label = new JLabel();
      label.setBorder(titledBorder);
      Container contentPane = frame.getContentPane();
      contentPane.add(label, BorderLayout.CENTER);
      frame.setSize(550, 300);
      frame.setVisible(true);
   }
}

Output

Code Explanation

The above program begins by creating a JFrame object, which is your application window. We then create a LineBorder with a specified color. To add a title to this border, we use the TitledBorder class, passing the LineBorder and the title text. The title position is set to appear above the top border line by calling the setTitlePosition() method with TitledBorder.ABOVE_TOP.
Next, a JLabel is created, and the customized TitledBorder is set as its border. The JLabel is then added to the content pane of the JFrame using the BorderLayout.CENTER layout

Updated on: 2024-09-11T12:25:16+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements