我想知道我将如何添加一个JPanel到JFrame,并确保它是中心,并有一组大小对两侧的空隙?我可以在中心得到它,但它坚持边缘.
使用边框布局.将JPanel放在中心,然后分别在东/西和北/南位置使用Box.createHorizontalStrut(size)和Box.createVerticalStrut(size).
类似的东西:(从记忆中,可能不完全正确)
JPanel panel = new JPanel();
int gap = 20; //or whatever
frame.getContentFrame().setLayout(new BorderLayout());
frame.add(panel, BorderLayout.CENTER);
panel.add(Box.createHorizontalStrut(gap), BorderLayout.EAST);
panel.add(Box.createHorizontalStrut(gap), BorderLayout.WEST);
panel.add(Box.createVerticalStrut(gap), BorderLayout.NORTH);
panel.add(Box.createVerticalStrut(gap), BorderLayout.SOUTH);
Run Code Online (Sandbox Code Playgroud)