如何在Java Swing中创建圆角标题边框

4

我知道要创建一个标题边框,你需要这样做:

BorderFactory.createTitledBorder("  Your Title  ");

然而,这样创建的边框是一个矩形边框,而我需要的是带有圆角的矩形。

根据我的理解,您可以通过以下方法创建自定义边框:

class CustomBorder implements Border
{
  ...
}

问题在于我不确定如何编写覆盖该方法的代码:
public void paintBorder(Component component, Graphics g, int x, int y, int width, int height)

或者更好的方法是,是否有一种方法可以不实现自己的Border类来完成这项工作?如果没有,那么您将如何编写自定义Title Border?我可以绘制一个带圆角的矩形,但是如何做到让标签也有空间呢?

请忽略这个问题。一旦您创建一个RounderBorder类,Swing将为您删除标题文本下方的边框。 - Stephane Grenier
实际上请忽略我的上一个评论。只有当您使用BorderFactory创建边框时,例如LineBorder,它才会这样做。看来现在是时候去研究一下LineBorder是如何进行绘制的了... - Stephane Grenier
2个回答

7

可以通过向TitledBorder的构造函数传递一个圆角边框来创建带有圆角边缘的标题边框,而无需实现自己的Border类。请尝试以下操作:

LineBorder roundedLineBorder = new LineBorder(Color.black, 5, true);
TitledBorder roundedTitledBorder = new TitledBorder(roundedLineBorder, "Title");

3
虽然这个帖子已经有点老了,但是也许会有一些偶然发现它的人会发现这个解决方案很有用:
你可以给任何边框添加标题:
  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"));
    

现在您应该看到自定义的边框,并在其上方使用您正在使用的Look&Feel的默认设置的标题。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接