2017-01-03 132 views
1

我有一個具有BoxLayout(頁面軸)的JPanel,我想佈置兩個組件,一個在另一個之上。BoxLayout添加左邊距

enter image description here

我的問題是保證金的大lipsum框的左側,我怎麼能擺脫嗎?如果我不添加頂部組件,則沒有餘量。

enter image description here

這是我的代碼,所述第二圖像是通過不添加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()倒是

+2

'這是我的代碼' - 發佈一個合適的[mcve]來演示問題。我們無法編譯/執行提供的代碼。 – camickr

回答

1

儘管我無法確定觀察到的行爲來自何處,但預期的顯示可以通過使用中間值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 
+0

我會試試這個,謝謝(開發機器沒電了) –

1

我的問題是保證金的大lipsum框的左側,我怎麼能擺脫嗎?

您需要使組件的對齊保持一致。這是所有組件的對齊「X」屬性應該保持對齊。

我猜JLabel的中央對齊,所以你需要使用:

descLabel.setAlignmentX(JLabel.LEFT_ALIGNMENT); 

的詳細信息和示例,請參見從How to Use BoxLayout Swing的教程Fixing Alignment Problems部分。