更改 JLabel 的一部分的字体?

Change font of a part of a JLabel?

我只想 将 JLabel 的前两个单词更改为与 JLabel 其余部分不同的字体。我发现我可以制作一个 JPanel,并在其中包含两个具有不同字体的 JLabel。我不能使用这种方式,因为我只能有一个 JLabel(这是因为我有一个鼠标侦听器,它根据不同的其他 JLabel 的入口或出口更改该 JLabel 的文本,这些 JLabel 位于单独的 JPanel 中)。有什么办法吗?我试过这个(将一个 JLabel 并排添加到另一个 JLabel):

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

但这没有用。我也试过把它变成一个字符串:

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

但是你不能改变字符串的字体...

两种方法是:

  1. 使用两个独立的JLabels
  2. JComponent 支持 HTML,因此您可以简单地使用字体标签来更改文本的外观。 http://docs.oracle.com/javase/tutorial/uiswing/components/html.html

尝试将 HTML StringJLabel 一起使用:

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);
      }
    });
  }
}

This is the line with the error

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

问题是您需要转义引号 size=\"6\".