How to add padding to a JPanel with a border

22,324

You can take a look at 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));

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

Share:
22,324

Related videos on Youtube

jobukkit
Author by

jobukkit

Updated on July 09, 2022

Comments

  • jobukkit
    jobukkit almost 2 years

    I want to add padding to some JPanels. I found this answer: 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 TitledBorder in this case)

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

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

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

    • nIcE cOw
      nIcE cOw almost 11 years
      +1, to the hard work you had done before posting the question :-) though, as stated previously this will come in some time
  • jobukkit
    jobukkit almost 11 years
    Thanks, CompoundBorder was just what I needed!