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 itsContentPane
doesn't implementsBorders
, this is prehistoricComponenet
put directly there
JPanel
withEmptyBorders
for
Java5
and higher isn't required to call forContentPane
(only forsetBackground:-)
, you can directly addJComponents
to theJFrame#add(myJComponent)
, noticeSwing Top-Level Containers
have got implementedBorderLayout
by default
Author by
Admin
Updated on June 04, 2022Comments
-
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 about 12 yearsJPanel i tried like above edit. But i do not have transparent container while using JPanel instead of Container.
-
ring bearer about 12 yearsWhat do you mean by "transparency" - please edit your question with what you tried and what was the issue