英文:
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中列出所有可用的字体系列名称?
和 如何随机选择数组的一个索引?
。您应该总是尝试将问题分解成更小的子问题。
我制作了一个整洁的函数,可以为您挑选一个随机字体系列的名称。如果要渲染的文本语言不是英语,请将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)];
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论