Ruchir Baronia
Ruchir Baronia

Reputation: 7561

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...

Upvotes: 2

Views: 7185

Answers (2)

user2575725
user2575725

Reputation:

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\".

Upvotes: 5

user4668606
user4668606

Reputation:

Two approaches would be:

  1. use two separate JLabels
  2. JComponent supports HTML, so you could simply use font tags to change the appeareance of the text. http://docs.oracle.com/javase/tutorial/uiswing/components/html.html

Upvotes: 3

Related Questions