如何在Java中生成随机字体?

huangapple go评论67阅读模式
英文:

How to generate a random font in java?

问题

我完全不了解Java和编码,我需要制作一个程序,每次随机使用不同的字体显示特定的文本。

英文:

I'm completely new to java and coding in general and I need to make a program display certain text using different fonts each time randomly.

答案1

得分: 0

这个问题应该分成两个部分。如何在Java中列出所有可用的字体系列名称?如何随机选择数组的一个索引?。您应该总是尝试将问题分解成更小的子问题。

以下是两个问题的答案:AB

我制作了一个整洁的函数,可以为您挑选一个随机字体系列的名称。如果要渲染的文本语言不是英语,请将Locale.ENGLISH替换为您的语言。

private static final Random RANDOM = new Random();

private static String pickRandomFontFamily() {
    String[] availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(Locale.ENGLISH);

    return availableFonts[RANDOM.nextInt(availableFonts.length)];
}
英文:

This question should be split into two parts. How can I list all available font family names in Java? and How to pick a random index of an array?. You should always try to split your problems into separate smaller sub-problems.

Here are the answers to both problems: A and B.

I made a neat function out of it which picks you the name of a random font family. If the language of the text that should be rendered is not English, replace Locale.ENGLISH with your language.

private static final Random RANDOM = new Random();

private static String pickRandomFontFamily() {
    String[] availableFonts = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames(Locale.ENGLISH);

    return availableFonts[RANDOM.nextInt(availableFonts.length)];
}

huangapple
  • 本文由 发表于 2020年10月23日 04:33:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/64490124.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定