首页 > 解决方案 > Java swing背景色填充边框外

问题描述

我正在构建一个 Java Swing 应用程序,我正在尝试在边框内实现背景色,

出于某种原因,它会溢出到边界之外,如您在此处看到的:

在此处输入图像描述

仅供参考,我需要保留 TitleBorder ->“TitledBorder.TOP”而不是“BELOW_TOP”

使用带有 Java SDK 8 的 IntelliJ IDEA 构建

感谢您的时间

标签: javaswingjframeborder

解决方案


for some reason it spills outside the border

That is the way Swing painting works.

All Swing components have a parent / child relationship. So the top level component is painted, then the child is painted on top of the parent etc all the way down the parent/child tree. So each child overrides the background of its parent.

Read the section from the Swing tutorial on A Closer Look at the Painting Mechanism

  1. So first the background of the panel is painted.
  2. then the border is painted on top of the panel. In the case of a TitleBorder only the text and line is painted on top of the background.

If this is not acceptable to you then you would need to create a custom Border that would first:

  1. paint the outer area of the Border in the same color as the background of the parent component.

  2. Then draw the TitleBorder.

Or, maybe you could somehow do this by using a CompoundBorder.

Read the section from the Swing tutorial on How to Use Borders for more information.


推荐阅读