How can I set the insets of a JFrame?

2020-08-17 18:09发布

Is there a way to set the insets of a JFrame? I tried

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

and

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

but none of them seem to work.

5条回答
该账号已被封号
2楼-- · 2020-08-17 18:44

As this question does not have a definitive answer yet you can do it like basiljames said here. The correct way to do it would be to extend a JFrame and then override the getInsets() method.

For example

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();
    }
}
查看更多
劳资没心,怎么记你
3楼-- · 2020-08-17 18:50

You have to create an Object of LayOutConstraint and set its Insets. Like in below example I have used GridBagLayout() and used GridBagConstraint() object.

    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);
查看更多
Fickle 薄情
4楼-- · 2020-08-17 18:58

you can create a main JPanel and insert everything else into it.

Then you can use BorderFactory to create EmptyBorder or LineBorder.

see this answer: https://stackoverflow.com/a/17925693/8953378

查看更多
Luminary・发光体
5楼-- · 2020-08-17 19:00

Overriding the Insets of JFrame would not be the soultion to your actual problem. To answer your question, you cannot set the Insets of JFrame. You should extend JFrame and override the getInsets method to give the insets you require.

查看更多
混吃等死
6楼-- · 2020-08-17 19:01
JPanel contentPanel = new JPanel();

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

contentPanel.setBorder(padding);

yourFrame.setContentPane(contentPanel);

So basically, contentPanel is the main container of your frame.

查看更多
登录 后发表回答