java 如何向带有边框的 JPanel 添加填充

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17925609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 19:38:09  来源:igfitidea点击:

How to add padding to a JPanel with a border

javaswingjpanelborderpadding

提问by stommestack

I want to add padding to some JPanels. I found this answer: https://stackoverflow.com/a/5328475/1590323

我想向某些JPanels添加填充。我找到了这个答案:https: //stackoverflow.com/a/5328475/1590323

It worked fine for a panel without a border. But how do I do it for a panel that already has a border? (A TitledBorderin this case)

它适用于没有边框的面板。但是对于已经有边框的面板,我该怎么做呢?(TitledBorder在这种情况下是A )

I tried:

我试过:

JPanel mypanel = new MyPanel(); // Panel that I am going to add a TitledBorder to, but needs padding
mypanel.setBorder(new EmptyBorder(10,10,10,10));
JPanel mypanel_container = new JPanel();
TitledBorder border = BorderFactory.createTitledBorder(BorderFactory.createRaisedBevelBorder(), "My panel");
border.setTitleJustification(TitledBorder.LEADING);
mypanel_container.setBorder(border);
mypanel_container.add(mypanel);
this.add(mypanel_container);

(In short: Adding an EmptyBorderto the panel that should have a TitledBorder, then make another panel with the TitledBorderand add the first panel to that, and then use that panel)

(简而言之:向EmptyBorder应该有 的面板添加TitledBorder,然后使用 制作另一个面板TitledBorder并将第一个面板添加到该面板,然后使用该面板)

But then I got way too large padding that ignored the contructor values of the EmptyBorder.

但是后来我得到了太大的填充,忽略了EmptyBorder.

So how do I add padding to a JPanel with a graphical border?

那么如何向带有图形边框的 JPanel 添加填充呢?

回答by NiziL

You can take a look at CompoundBorder.

你可以看看CompoundBorder

A composite Border class used to compose two Border objects into a single border by nesting an inside Border object within the insets of an outside Border object. For example, this class may be used to add blank margin space to a component with an existing decorative border:

Border border = comp.getBorder();
Border margin = new EmptyBorder(10,10,10,10);
comp.setBorder(new CompoundBorder(border, margin));

一个复合 Border 类,用于通过将内部 Border 对象嵌套在外部 Border 对象的插图中,将两个 Border 对象组合成单个边框。例如,此类可用于向具有现有装饰边框的组件添加空白边距空间:

Border border = comp.getBorder();
Border margin = new EmptyBorder(10,10,10,10);
comp.setBorder(new CompoundBorder(border, margin));

Of course, you can also use BorderFactory#createCompoundBorder(border, margin).

当然,您也可以使用BorderFactory#createCompoundBorder(border, margin).