2017-07-25 61 views
1

我有一個JLabel,其中包含一些html格式的文本。最後嘗試在JTable中包裝行。但是,我的問題可以通過JLabel簡化。在HTML格式中是這樣的:JLabel中的HTML不會在瀏覽器中顯示相同的結果

<html> 
<body style='width: 250px;'> 
    <p style='word-wrap: break-word;'>some string</p> 
</body> 
</html> 

在瀏覽器中運行的一切這正常工作,甚至有很長的一個字串,它包裝,因爲我希望它。如果我把這個在JLabel像這樣:

import java.awt.BorderLayout; 
import java.awt.Dimension; 

import javax.swing.JFrame; 
import javax.swing.JLabel; 
import javax.swing.SwingUtilities; 

public class HtmlInLabelExample extends JFrame { 

    private static final long serialVersionUID = 2194776387062775454L; 

    public HtmlInLabelExample() { 
     this.setTitle("HTML within a JLabel"); 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.setLayout(new BorderLayout()); 
     this.setSize(new Dimension(300, 100)); 
     this.setLocationRelativeTo(null); 

     String HTML_1 = "<html><body style='width: "; 
     String HTML_2 = "px;'><p style='word-wrap: break-word;'>"; 
     String HTML_3 = "</p></body></html>"; 

     String strWithSpaces = "This is a long String that should be wrapped and displayed on multiple lines. However, if this was only one really long word, that doesnt work."; 
     String strWithoutSpaces = "ThisisalongStringthatshouldbewrappedanddisplayedonmultiplelines.However,ifthiswasonlyonereallylongword,thatdoesntwork."; 
     JLabel lblHtml = new JLabel(); 

     lblHtml.setText(HTML_1 + String.valueOf(250) + HTML_2 + strWithoutSpaces + HTML_3); 

     this.add(lblHtml); 
     this.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new HtmlInLabelExample(); 
      } 

     }); 
    } 

} 

包裝作品,但它沒有打破其間的話,就好像我wouldnt使用樣式=「自動換行:打破字;.

有人可以向我解釋爲什麼html格式在瀏覽器中工作不同(我嘗試了最常見的),並且如果有解決方法嗎?

回答

2

有人能向我解釋爲什麼HTML格式的瀏覽器的工作方式不同..

鞦韆只支持一個子集HTML 3.2 &非常簡單的樣式。我會感到驚訝,如果它沒有支持word-wrap: break-word;

..如果有辦法解決它?

嵌入瀏覽器。 Swing不提供一個,但是Java-FX does

+1

'WebView'可以嵌入到Swing中,例如[https://stackoverflow.com/a/31576647/230513]。 – trashgod

0

JLabel是一個Swing組件,所以它對CSS的支持可能不會達到最新的標準甚至是之前的標準。技術的世界已經那種從鞦韆上移...

相關問題