将 JTextField 字体设置为在 JFontChooser 中选择的字体

Setting JTextField font to what is selected in JFontChooser

我最近发现了这个组件,它非常好,正是我想要的,但我不确定如何使用它。

如何将 JTextField 的字体设置为用户在 JFontChooser 中选择的字体?

这是我能找到的所有内容:

The JFontChooser class is a swing component for font selection. This class has JFileChooser like APIs. The following code pops up a font chooser dialog.

JFontChooser fontChooser = new JFontChooser();
int result = fontChooser.showDialog(parent);
if (result == JFontChooser.OK_OPTION)
{
  Font font = fontChooser.getSelectedFont(); 
  System.out.println("Selected Font : " + font); 
} 

我想要它做的是:

更新:tNumber.setFont(new font(""Tahoma", Font.BOLD, 300));

用户在字体选择器中选择的字体样式和大小。

好吧,你们非常亲密,

JFontChooser fontChooser = new JFontChooser();
int result = fontChooser.showDialog(parent);
if (result == JFontChooser.OK_OPTION)
{
  Font font = fontChooser.getSelectedFont(); 
  tNumber.setFont(font.deriveFont(Font.BOLD, 300f));//This is the line I added.
} 

请参阅 setFont and deriveFont 文档。

使用 font.deriveFont(Font.BOLD, 300f) 根据当前字体和您提供的属性创建新字体。

tNumber.setFont(font.deriveFont(Font.BOLD, 300f));

有关详细信息,请参阅 Font#deriveFont(float, int)