问题
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.
回答1:
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.
回答2:
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.
回答3:
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);
回答4:
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();
}
}
回答5:
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
来源:https://stackoverflow.com/questions/14117481/how-can-i-set-the-insets-of-a-jframe