2016-07-12 75 views
0

這個問題是從我previous question的JLabel不顯示HTML正確

跟進我有一個JLabel裏面坐了HTML文本。但是,HTML內容沒有正確顯示。 JLabel應該是26x26像素,並在右下角顯示一個數字。我的代碼似乎沒有在正確的位置顯示數字,其高度似乎被截斷。

這裏是我的代碼:

final String buffBadgeStyles = "<style>" 
+ "#container {height:26px; width:26px; background-color: red; position:relative;}" 
+ "#bottom {position:absolute; bottom:0; right:0;}" 
+ "</style>"; 

buffSlot_6 = new JLabel(); 
buffSlot_6.setBorder(new LineBorder(Color.BLACK)); 
buffSlot_6.setHorizontalAlignment(SwingConstants.CENTER); 
buffSlot_6.setVerticalAlignment(SwingConstants.CENTER); 
buffSlot_6.setText("<html>" 
+ buffBadgeStyles 
+ "<body>" 
+ "<p id=\"container\"><span id=\"bottom\">2</span></p>" 
+ "</body></html>"); 
buffSlot_6.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); 
panel_playerBuffs.add(buffSlot_6); 

JLabel將意味着這個樣子 enter image description here 但我的代碼生成此enter image description here

有什麼想法?

+1

1)Swing的HTML/CSS實現是非常基本的。 2)爲了更快地獲得更好的幫助,請發佈[MCVE]或[簡短,獨立,正確的示例](http://www.sscce.org/)。 –

+1

你爲什麼使用HTML。您可以使用標籤的屬性來控制文本位置。閱讀API以瞭解控制文本水平/垂直位置的方法。 – camickr

+0

@camickr因爲我還需要在標籤的中間添加一個背景圖片。 JLabel API不允許字符串重疊圖像。 – Dragneel

回答

3

您可以通過使用輔助面板(即包裝標籤)併爲面板選擇適當的佈局來獲得此視圖。這樣你就不需要html。您應該將26像素大小設置爲包裝面板而不是標籤。

package so; 

import java.awt.BorderLayout; 
import java.awt.Color; 
import java.awt.Font; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.JPanel; 
import javax.swing.SwingConstants; 
import javax.swing.SwingUtilities; 
import javax.swing.border.LineBorder; 

public class Main { 

    public static void main(String[] args) { 

     SwingUtilities.invokeLater(() -> { 

      JFrame frame = new JFrame("Label test"); 

      JPanel helperPanel = new JPanel(); 

      frame.setContentPane(helperPanel); 
      helperPanel.setLayout(new BorderLayout()); 

      JLabel buffSlot_6 = new JLabel(); 
      buffSlot_6.setBorder(new LineBorder(Color.BLACK)); 
      buffSlot_6.setHorizontalAlignment(SwingConstants.RIGHT); 
      buffSlot_6.setVerticalAlignment(SwingConstants.BOTTOM); 
      buffSlot_6.setText("2"); 

      buffSlot_6.setFont(new Font("Comic Sans MS", Font.BOLD, 12)); 
      helperPanel.add(buffSlot_6, BorderLayout.CENTER); 

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
      frame.setLocationRelativeTo(null); 
      frame.setSize(100, 100); 
      frame.setVisible(true); 

     }); 
    } 
} 
+0

是的,我試圖不訴諸這種方法。我認爲會有一個更簡單的解決方案。總之,謝謝。 – Dragneel