如何向带有边框的JPanel添加填充 [英] How to add padding to a JPanel with a border

查看:153
本文介绍了如何向带有边框的JPanel添加填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

它对于没有边框的面板效果很好.但是,对于已经有边框的面板,我该如何做呢? (在这种情况下为TitledBorder

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

我尝试过:

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);

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

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

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

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

所以如何向带有图形边框的JPanel添加填充?

推荐答案

您可以查看

You can take a look at CompoundBorder.

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

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));

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

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

这篇关于如何向带有边框的JPanel添加填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆