How do I add padding with Container?

19,067

Solution 1

You can override Container#getInsets, although you should be using Swing components.

Solution 2

Can't you simply add a JPanel to contain everything and set empty border on that ?

 JPanel containerPanel = new JPanel();
 containerPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
 containerPanel.setLayout(new BorderLayout());
 //panel to test
 JPanel testPanel = new JPanel();
 testPanel.setBackground(Color.blue);        
 containerPanel.add(testPanel,BorderLayout.CENTER);

 //assuming you are extending JFrame
 getContentPane().setLayout(new BorderLayout());
 getContentPane().add(containerPanel, BorderLayout.CENTER);

Solution 3

  • JFrame / Frame and its ContentPane doesn't implements Borders, this is prehistoric Componenet

  • put directly there JPanel with EmptyBorders

  • for Java5 and higher isn't required to call for ContentPane (only for setBackground:-), you can directly add JComponents to the JFrame#add(myJComponent), notice Swing Top-Level Containers have got implemented BorderLayout by default

Share:
19,067
Admin
Author by

Admin

Updated on June 04, 2022

Comments

  • Admin
    Admin almost 2 years

    I am trying to make on top some padding but how to do this with Container?

        JFrame frame = super.screen.getFullScreenWindow();
        //Container contentPane = frame.getContentPane();
        //JPanel contentPane = new JPanel();
    
        // Make sure the content pane is transparent
        if (contentPane instanceof JComponent) {
            ((JComponent)contentPane).setOpaque(false);
        } 
        else {
          // ??
        }
    
        contentPane.setBorder(new EmptyBorder(10, 10, 10, 10) );
        //frame.getContentPane().add(contentPane, BorderLayout.CENTER);
    

    Output

     [javac] symbol  : method setBorder(javax.swing.border.EmptyBorder)
     [javac] location: class java.awt.Container 
     [javac] contentPane.setBorder(new EmptyBorder(10, 10, 10, 10) );
     [javac]
    
  • Admin
    Admin about 12 years
    JPanel i tried like above edit. But i do not have transparent container while using JPanel instead of Container.
  • ring bearer
    ring bearer about 12 years
    What do you mean by "transparency" - please edit your question with what you tried and what was the issue