Search code examples
javaswinguser-interfacefontsjlabel

Change font of a part of a JLabel?


I want to change only the first two words of a JLabel to a different font than the rest of the JLabel. I have found that I could make a JPanel, and have two JLabels with different fonts in it. I cannot use this way, because I can only have one JLabel (This is since I have a mouse listener which changes the text of that JLabel based on entrance or exit of different other JLabels, which are in a seperate JPanel). Is there any way? I have tried this (adding a JLabel side by side to another JLabel):

JLabel Giraffesays = new JLabel("Giraffe says:");
        Giraffesays.setFont(new Font("TimesRoman", Font.BOLD, 60)); 
        status.setText(Giraffesays +"Hi!"); //status is a JLabel

but this didn't work. I also tried making it a string:

String Giraffesays = "Giraffe says:
        Giraffesays.setFont(new Font("TimesRoman", Font.BOLD, 60)); 
        status.setText(Giraffesays +"Hi!"); //status is a JLabel

But you cannot change the font of a String...


Solution

  • Try using HTML String with JLabel:

    import javax.swing.SwingUtilities;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    
    public class Test {
      public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
          @Override public void run() {
            JFrame frm = new JFrame("Text formatting");
            frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            String giraffesays = "<html><span style=\"font-family:Arial;font-size:13px;\">Giraffe says :</span>Hi there!</html>";
            frm.getContentPane().add(new JLabel(giraffesays));
            frm.pack();
            frm.setLocationByPlatform(true);
            frm.setVisible(true);
          }
        });
      }
    }
    

    enter image description here

    This is the line with the error

    String giraffesays = "<html><font size="6"><span style=\"font-family:Arial;\">Giraffe says :</font></span></html>";
    

    Problem is you need to escape the quotes size=\"6\".