2011-09-01 15 views
10

Ho appena avviato il porting della mia app Swing da OS X a Windows e le cose sono dolorose con JLabel s.JLabel html testo ignora setFont

Ho notato che il carattere specificato su setFont viene ignorato se il testo dell'etichetta è HTML (ciò non accade sul Mac). La formattazione HTML è ESTREMAMENTE utile per la leggibilità su display complicati.

In circostanze normali, specificarei il carattere in un tag HTML, ma il font che sto utilizzando viene caricato in fase di esecuzione usando Font.createFont con un ttf fuori dal JAR. Ho provato a utilizzare il nome del carattere caricato nel tag del font, ma non ha funzionato.

C'è un modo per utilizzare uno awt.Font caricato con un JLabel html-ified su Windows?

Ecco un esempio. Non è possibile condividere carattere della mia domanda, ma ho appena eseguito con questo (una TTF puro) e lo stesso comportamento accade:

http://www.dafont.com/sophomore-yearbook.font

import java.awt.Font; 
import java.io.File; 
import javax.swing.*; 

public class LabelTestFrame extends JFrame { 

     public LabelTestFrame() throws Exception { 
       boolean useHtml = true; 
       String fontPath = "C:\\test\\test_font.ttf"; 
       JLabel testLabel = new JLabel(); 
       Font testFont = Font.createFont(Font.TRUETYPE_FONT, new File(fontPath)).deriveFont(18f); 
       testLabel.setFont(testFont); 
       if (useHtml) testLabel.setText("<html>Some HTML'd text</html>"); 
       else testLabel.setText("Some plaintext"); 
       getContentPane().add(testLabel); 
       setSize(300,300); 
     } 

     public static void main(String[] args) { 
       SwingUtilities.invokeLater(new Runnable() { 
         @Override 
         public void run() { 
           try {new LabelTestFrame().setVisible(true);} 
           catch (Exception e) {e.printStackTrace();} 
         } 
       }); 
     } 

} 

EDIT: abbastanza interessante, se uso uno dei il file ttf dalla cartella lib/fonts di JRE (in questo caso uno dei font Lucida qui rinominato test_java.ttf) questo snippet produce risultati identici con il booleano on e off.

public LabelTestFrame() throws Exception { 
    boolean useHtml = false; 
    String fontPath = "C:\\test\\test_java.ttf"; 
    JLabel testLabel = new JLabel(); 
    Font testFont = Font.createFont(Font.TRUETYPE_FONT, new File(fontPath)).deriveFont(18f); 
    testLabel.setFont(testFont); 
    if (useHtml) testLabel.setText("<html><b>Some HTML'd text</b></html>"); 
    else testLabel.setText("Some plaintext"); 
    getContentPane().add(testLabel); 
    setSize(300,300); 
} 

public static void main(String[] args) { 
    SwingUtilities.invokeLater(new Runnable() { 
     @Override 
     public void run() { 
      try {new LabelTestFrame().setVisible(true);} 
      catch (Exception e) {e.printStackTrace();} 
     } 
    }); 
} 

EDIT 2: Il metodo qui descritto per l'impostazione predefinita di carattere JLabel ha esattamente lo stesso problema (testo in chiaro mostra bene, il testo html'd non lo fa): Changing default JLabel font

EDIT 3: ho ho notato che anche i font casuali di dafont funzioneranno se sono installati sul sistema (anche con questo codice esatto, dove sono caricato una copia del file ttf [ora installato] da un file).

+0

Potrebbe essere possibile includere un [sscce] (http://www.sscce.org)? Nel frattempo, se non lo hai già fatto, leggi il tutorial [Come usare HTML in Swing Components] (http://download.oracle.com/javase/tutorial/uiswing/components/html.html). – mre

+0

È molto probabile che 'Font.createFont' sta riscontrando problemi.'' SetFont() 'di' Jlabel' è garantito per impostare il font - come suggerisce @mre, l'esempio potrebbe aiutare a rispondere meglio a questo. –

+0

So che Font.createFont funziona perché se si impostaText ("esempio") su JLabel viene visualizzato il carattere caricato, ma se si impostaText (" esempio") viene utilizzato il tipo di carattere predefinito Jolly di Swing. Questo conta come una sscce? –

risposta

12

registerFont()

Ho trovato questo gioiellino mentre cercavo su Google se potevo copiare un .ttf in JRE in fase di esecuzione. Fa esattamente quello che dovrebbe. Se si utilizza Font.createFont per caricare un tipo di carattere in fase di esecuzione, basta fare:

GraphicsEnvironment.getLocalGraphicsEnvironment().registerFont(myCreatedFont)

per registrarlo con JRE.

Ciò consente al font di apparire in testo HTML e testo in chiaro su Windows!

+0

+1 ['createFont () '] (http://download.oracle.com/javase/6/docs/api/java/awt/Font.html#createFont%28int,%20java.io.InputStream%29) menziona questo, ma è un po ' vago. – trashgod

+0

Lo menziona solo nel javadoc Java 6. Accidenti a te Google per aver mostrato 1.4 javadoc prima! –

+0

Non posso incolpare Google per lo Snoracle Shuffle! :-) – trashgod

4

Per riferimento, ecco ciò che si vede su Mac OS X.

enter image description here

A titolo di confronto, ecco la visualizzazione su Ubuntu 10, OpenJDK 6.

enter image description here

import java.awt.Font; 
import java.awt.GridLayout; 
import java.io.File; 
import javax.swing.*; 

public class LabelTestFrame extends JFrame { 

    public LabelTestFrame() throws Exception { 
     this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     this.setLayout(new GridLayout(0, 1)); 
     String fontPath = "SophomoreYearbook.ttf"; 
     Font testFont = Font.createFont(
      Font.TRUETYPE_FONT, new File(fontPath)).deriveFont(18f); 
     JLabel label1 = new JLabel("<html>Some HTML'd text</html>"); 
     label1.setFont(testFont); 
     this.add(label1); 
     JLabel label2 = new JLabel("Some plaintext"); 
     this.add(label2); 
     this.pack(); 
     this.setLocationRelativeTo(null); 
    } 

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

      @Override 
      public void run() { 
       try { 
        new LabelTestFrame().setVisible(true); 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 
} 
+0

sì, OS X funziona come previsto per me. –

+0

Speravo che un facile confronto side-by-side potesse far luce. Il file _any_ '.ttf' funziona su Windows? – trashgod

+0

sì, il builtin (già installato da JRE) Lucida ttf fa la cosa giusta per me. Sembra che Linux stia rompendo anche per te (è Sun Java o OpenJDK?). –