How to create two borders for a single component in Java?


To create two borders for a single component, use the createCompoundBorder() method in Java. Here, we have created LineBorder nd TitledBorder −

LineBorder lineBorder = new LineBorder(Color.red);
TitledBorder titleBorder = new TitledBorder("Demo Title");
Border border = BorderFactory.createCompoundBorder(lineBorder, titleBorder);

Now, set both the borders for a single component −

JButton button = new JButton("two borders");
button.setBorder(border);

The following is an example to create two borders for a single component −

Example

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
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);
      Border raisedBorder = new EtchedBorder(EtchedBorder.RAISED);
      LineBorder lineBorder = new LineBorder(Color.red);
      TitledBorder titleBorder = new TitledBorder("Demo Title");
      Border border = BorderFactory.createCompoundBorder(lineBorder, titleBorder);
      JButton raisedButton = new JButton("Raised Border");
      raisedButton.setBorder(raisedBorder);
      JButton button = new JButton("two borders");
      button.setBorder(border);
      Container contentPane = frame.getContentPane(); contentPane.add(raisedButton,BorderLayout.WEST);
      contentPane.add(button,BorderLayout.EAST);
      frame.setSize(600, 300);
      frame.setVisible(true);
   }
}

Output

Updated on: 30-Jul-2019

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements