Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a rounded title border in Java Swing

Tags:

java

swing

I do understand that to create a title border, you do something like:

BorderFactory.createTitledBorder("  Your Title  ");

However this creates a rectangle border whereas I need a rectangle with curved corners.

Now from what I understand you can create your own custom border by:

class CustomBorder implements Border
{
  ...
}

The problem is that I'm not sure how to write the code that overrides the method:

public void paintBorder(Component component, Graphics g, int x, int y, int width, int height)

Or better yet, is there a way to do it without implementing your own Border class? And if not, how would you write that custom Title Border? I'm ok with drawing a rectangle with rounded corners, but how do you do it so that there's space for the label too?

like image 552
Stephane Grenier Avatar asked Dec 28 '22 13:12

Stephane Grenier


2 Answers

It is possible to create a title border with rounded edges without implementing your own Border class. Simply pass a rounded border to TitledBorder's constructor. Try the following:

LineBorder roundedLineBorder = new LineBorder(Color.black, 5, true);
TitledBorder roundedTitledBorder = new TitledBorder(roundedLineBorder, "Title");
like image 169
EMurnane Avatar answered Jan 10 '23 06:01

EMurnane


Although this thread is a bit old already, maybe someone who stumbles over it might find the solution useful:

You can add a title to any border you want:

  1. implement your custom border class public class MyBorder extends AbstractBorder {... and in the public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) method you can paint your own custom border on the Graphics context

  2. create an instance of this custom border

    Border myborder = new MyBorder();
    
  3. create the TitledBorder using your custom border as a template and add it to the object you want (in this case a JPanel:

    jPanel1.setBorder(BorderFactory.createTitledBorder(myborder , "Border title"));
    

You should now see your custom Border and above that the Title with the default settings of the Look&Feel you are using.

like image 27
Larzan Avatar answered Jan 10 '23 05:01

Larzan