我有一个带有 BoxLayout
(页面轴)的 JPanel,我想布置两个组件,一个位于另一个之上。
我的问题是大嘴唇框左侧的边距,我怎样才能摆脱这个问题?如果我不添加顶部组件,就没有余量。
这是我的代码,第二个图像是通过不添加 headerPanel
创建的:
JLabel commandLabel = new JLabel(command);
JLabel paramLabel = new JLabel(params);
JLabel descLabel = new JLabel("<html><body style='width: 200px;'>" + description + "</body></html>");
Font baseFont = commandLabel.getFont(), commandFont, paramFont, descFont;
commandFont = baseFont.deriveFont(Font.BOLD);
paramFont = baseFont.deriveFont(Font.ITALIC);
descFont = baseFont.deriveFont(Font.PLAIN);
commandLabel.setFont(commandFont);
paramLabel.setFont(paramFont);
descLabel.setFont(descFont);
descLabel.setAlignmentX(LEFT_ALIGNMENT);
descLabel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke()));
JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
headerPanel.add(commandLabel);
headerPanel.add(paramLabel);
this.add(headerPanel);
this.add(descLabel);
此类扩展了 JPanel
,并添加到 JFrame
,这只是 pack()
的
最佳答案
虽然我无法判断观察到的行为来自何处,但可以通过使用中间 JPanel
来包含标签来实现预期的显示,而不是添加 JLabel
直接:
JLabel commandLabel = new JLabel(command);
JLabel paramLabel = new JLabel(params);
JLabel descLabel = new JLabel("<html><body style='width: 200px;'>" + description + "</body></html>");
Font baseFont = commandLabel.getFont(), commandFont, paramFont, descFont;
commandFont = baseFont.deriveFont(Font.BOLD);
paramFont = baseFont.deriveFont(Font.ITALIC);
descFont = baseFont.deriveFont(Font.PLAIN);
commandLabel.setFont(commandFont);
paramLabel.setFont(paramFont);
descLabel.setFont(descFont);
descLabel.setAlignmentX(LEFT_ALIGNMENT);
descLabel.setBorder(BorderFactory.createStrokeBorder(new BasicStroke()));
JPanel headerPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
JPanel descPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));// added
headerPanel.add(commandLabel);
headerPanel.add(paramLabel);
descPanel.add(descLabel);// added
this.add(headerPanel);
this.add(descPanel);// modified
关于java - BoxLayout 添加左边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41444875/