How do I add a margin outside the border of a component in Swing?

前端 未结 2 1686
不知归路
不知归路 2021-02-20 11:33

I use multiple components that has a border painted. Is there any easy way to add a margin to the component so that the borders aren\'t painted so close to eachother?

2条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 12:23

    Another way to get what you want is to:

    1. get the current Border of your component
    2. if null, set an EmptyBorder for your component
    3. if not null, create a new CompoundBorder (with an EmptyBorder and the current Border of the component) and set it for the component

    In code, that should look like that (sorry I haven't tested it):

    Border current = component.getBorder();
    Border empty = new EmptyBorder(top, left, bottom right);
    if (current == null)
    {
        component.setBorder(empty);
    }
    else
    {
        component.setBorder(new CompoundBorder(empty, current));
    }
    

    Where:

    • component is the Swing component to which you want to add a margin
    • top, left, bottom, right are the pixels amounts you want to add around your component

    Note that this method might have an impact (size, alignment) on the form layout, depending on the LayoutManager you are using. But I think it is worth trying.

提交回复
热议问题