如何设置JFrame的插入?

10

有办法设置 JFrame 的插入值吗? 我试过:

frame.getContentPane().getInsets().set(10, 10, 10, 10);

并且

frame.getInsets().set(10, 10, 10, 10);

但是它们都似乎没有起作用。


1
如果使用JPanel作为内容面板,只需使用panel.setBorder(new EmptyBorder(10,10,10,10)); - Andrew Thompson
如果OP想要在框架上设置插图,为什么不覆盖getInsets()呢? - Dan
@Dan 1) “不要这样做”是一个有效的答案吗?2) 组合优于继承 3) 我们很少能够使用单个布局来创建应用程序,因此最好创建一个主面板作为内容面板。4) 但除了这三个令人信服的理由外,我想没有其他理由了。 - Andrew Thompson
5个回答

28
JPanel contentPanel = new JPanel();

Border padding = BorderFactory.createEmptyBorder(10, 10, 10, 10);

contentPanel.setBorder(padding);

yourFrame.setContentPane(contentPanel);

总的来说,contentPanel 是你的窗口的主要容器。


我没有使用getContentPane方法,而是创建了一个名为contentPanelJPanel以便访问setBorder方法。 - Mark Vizcarra

4
重写 JFrame 的 Insets 不是解决您实际问题的方法。 回答您的问题,您不能设置 JFrame 的 Insets。 您应该扩展 JFrame 并重写 getInsets 方法以提供所需的 insets。

2
您需要创建一个LayOutConstraint对象并设置其Insets属性。就像下面的例子中使用了GridBagLayout()和GridBagConstraint()对象一样。
    GridBagConstraints c = new GridBagConstraints();
    JPanel panel = new JPanel(new GridBagLayout());
    c.insets = new Insets(5, 5, 5, 5); // top, left, bottom, right
    c.anchor = GridBagConstraints.LINE_END;

    // Row 1
    c.gridx = 0;
    c.gridy = 0;
    c.anchor = GridBagConstraints.LINE_START;
    panel.add(isAlgoEnabledLabel, c);

0

由于这个问题目前没有明确的答案,您可以像basiljames所说的那样在这里进行操作。正确的方法是扩展JFrame并覆盖getInsets()方法。

例如:

import javax.swing.JFrame;
import java.awt.Insets;

public class JFrameInsets extends JFrame {
    @Override
    public Insets getInsets() {
        return new Insets(10, 10, 10, 10);
    }

    private JFrameInsets()  {
        super("Insets of 10");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pack();
        setMinimumSize(getSize());
        setVisible(true);
    }

    public static void main(String[] args) {
        new JFrameInsets();
    }
}

这不是一个好的方式,因为在调整大小的情况下插入物会被破坏。 - Alon Gouldman

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接