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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:11:09  来源:igfitidea点击:

How do I add padding with Container?

javaswingawt

提问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 / Frameand its ContentPanedoesn't implements Borders, this is prehistoric Componenet

  • put directly there JPanelwith EmptyBorders

  • for Java5and higher isn't required to call for ContentPane(only for setBackground:-), you can directly add JComponentsto the JFrame#add(myJComponent), notice Swing Top-Level Containershave got implemented BorderLayoutby default

  • JFrame / FrameContentPane没有实现Borders,这是史前的Componenet

  • 直接就把那里JPanelEmptyBorders

  • forJava5和更高的不需要调用ContentPane(仅 for setBackground:-),您可以直接添加JComponentsJFrame#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 库要好得多。