java 如何使用 Container 添加填充?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9996018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I add padding with Container?
提问by ring bearer
I am trying to make on top some padding but how to do this with Container?
我正在尝试在顶部填充一些填充,但如何使用 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]
采纳答案by mre
You can override Container#getInsets, although you should be using Swing components.
您可以覆盖Container#getInsets,但您应该使用 Swing 组件。
回答by ring bearer
Can't you simply add a JPanel to contain everything and set empty border on that ?
您不能简单地添加一个 JPanel 来包含所有内容并在其上设置空边框吗?
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);
回答by mKorbel
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
JFrame / Frame
它ContentPane
没有实现Borders
,这是史前的Componenet
直接就把那里
JPanel
有EmptyBorders
for
Java5
和更高的不需要调用ContentPane
(仅 forsetBackground:-)
,您可以直接添加JComponents
到JFrame#add(myJComponent)
,通知默认Swing Top-Level Containers
已实现BorderLayout
回答by Snicolas
don't you prefer to use swing ? Components have a method to add margins. Swing is far better than the obsolete awt library.
你不喜欢使用swing吗?组件具有添加边距的方法。Swing 比过时的 awt 库要好得多。