求助:含两个子JPanel的JPanel设置内边距无效(GridBagLayout场景)
Java Swing布局问题:dataInputPanel内边距不生效的原因与解决办法
问题说明
- 现象:红色边框的
dataInputPanel无法显示内边距,无报错但设置不生效 - 目标:为
dataInputPanel设置上下左右各10的内边距
相关代码
Main类代码
public class Main { public static void main(String[] args) { JFrame win = new JFrame(); win.setTitle("Lord of the Rings - Battle Simulator"); win.setSize(500, 600); win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); win.setLayout(new GridLayout(2, 1)); win.setResizable(false); //------------- JPanel dataInputPanel = new JPanel(); dataInputPanel.setLayout(new GridLayout(1, 2, 10, 0)); //dataInputPanel.setBackground(Color.RED); dataInputPanel.setBorder(new LineBorder(Color.RED, 4, true)); JPanel battleOutupPanel = new JPanel(); //battleOutupPanel.setBackground(Color.GREEN); battleOutupPanel.setBorder(new LineBorder(Color.GREEN, 4, true)); //------------------------------------- int paddingSize = 50; Insets paddingInsets = new Insets(paddingSize, paddingSize, paddingSize, paddingSize); // Heroes Data Input Panel - dataInputPanel GridBagLayout 1 row, 2 columns JPanel heroesDataInputPanel = new JPanel(); //heroesDataInputPanel.setBackground(Color.YELLOW); heroesDataInputPanel.setBorder(new LineBorder(Color.YELLOW, 4, true)); GridBagConstraints gbc1 = new GridBagConstraints(); gbc1.gridx = 0; gbc1.gridy = 0; gbc1.insets = paddingInsets; dataInputPanel.add(heroesDataInputPanel, gbc1); // Beasts Data Input Panel - dataInputPanel - GridBagLayout 1 row, 2 columns JPanel beastsDataInputPanel = new JPanel(); //beastsDataInputPanel.setBackground(Color.ORANGE); beastsDataInputPanel.setBorder(new LineBorder(Color.ORANGE, 4, true)); GridBagConstraints gbc2 = new GridBagConstraints(); gbc2.gridx = 1; gbc2.gridy = 0; gbc2.insets = paddingInsets; dataInputPanel.add(beastsDataInputPanel, gbc2); //------------- win.add(dataInputPanel); win.add(battleOutupPanel); win.setVisible(true); } }
Win类代码
public class Win extends JFrame { }
Pnl类代码
public class Pnl extends JPanel { }
界面截图

问题原因
dataInputPanel设置的布局是GridLayout,但你使用了GridBagConstraints的insets属性来设置内边距——该属性仅在GridBagLayout布局下生效,因此内边距设置无效。
解决方案
方案一:切换布局为GridBagLayout
修改dataInputPanel的布局代码:dataInputPanel.setLayout(new GridBagLayout());此时原有的
GridBagConstraints.insets设置会正常生效。方案二:使用空边框实现内边距
若想保留GridLayout,可通过BorderFactory创建复合边框,既保留原有红色边框,又添加内边距:// 先保留原有的红色边框,再叠加空边框作为内边距 dataInputPanel.setBorder(BorderFactory.createCompoundBorder( new LineBorder(Color.RED, 4, true), BorderFactory.createEmptyBorder(10, 10, 10, 10) ));
内容的提问来源于stack exchange,提问作者OrlandoVSilva
相关产品推荐
相关产品推荐

