【发布时间】:2020-07-02 08:51:23
【问题描述】:
我想要达到的目标:
我想从javax.swing.UIManager 中可视化一些javax.swing.Icons。我在网上找到了UIManager-keys 的列表,它不仅会返回Icons,还会返回Strings、Colors 等。因此,在这一步中,我想过滤键列表,以便仅保留 Icon-keys。
我的方法:
我将UIManager 键的列表复制到一个文本文件中,并将其作为资源包含在我的Java 项目中。我成功读取了文件,所以我按行拆分文件内容并将它们添加到Strings 的ArrayList。现在我想流式传输这个ArrayList 的内容并通过UIManager.getIcon(Object key)-方法是否返回null 来过滤键...
我的问题
到目前为止:UIManager 总是返回null。我将所有键和UIManager 结果打印到控制台(请参阅我的代码中的“输出/测试 - 流键”)。如果我从控制台手动复制一个密钥(我知道应该可以工作)并将其粘贴到完全相同的代码中,它实际上可以工作(请参阅我的代码中的“输出/测试 - 单个密钥”)。
有趣的行为显示当我将 String 附加到要打印到控制台的键上时(请参阅“输出/测试 - 流键”下的变量“后缀”在我的代码中)。如果变量suffix 不以“\n”开头,则流中的以下打印方法将只打印suffix,不再显示其他内容。例如,如果我键入 String suffix = "test";,则只会从 .forEach(key->System.out.println(... + key + suffix); 打印“测试”但是,此行为不会出现在“输出/测试 - 单键”-示例中。
我不知道发生了什么,或者(在我看来)奇怪的行为是否与问题有关。感谢您的任何帮助!
来自“UIManagerKeys.txt”的片段: 以下是一些用于测试和重现性目的的键...
FileView.computerIcon
FileView.directoryIcon
FileView.fileIcon
FileView.floppyDriveIcon
FileView.hardDriveIcon
FormattedTextField.background
FormattedTextField.border
windowText
我的代码:
package main;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.UIManager;
public class Main {
public Main() {
}
public static void main(String args[]) {
ArrayList<String> uiKeys = new ArrayList<>();
String fileName = "recources/UIManagerKeys.txt";
ClassLoader classLoader = new Main().getClass().getClassLoader();
File file = new File(classLoader.getResource(fileName).getFile());
// Check: is File found?
System.out.println("File Found : " + file.exists());
try {
// Read File Content
String content = new String(Files.readAllBytes(file.toPath()));
// Split by line and collect
String[] keys = content.split("\n");
uiKeys.addAll(Arrays.asList(keys));
} catch (IOException e) {
System.out.println("Error: " + e);
}
// Output / Test - stream Keys
System.out.println("Total Number of Keys: " + uiKeys.size());
String suffix = ""; // Interesting behavior when String is not empty
uiKeys.stream()
.map(key -> key.replaceAll(" ", "").replaceAll("\n", "")) // Just to be sure
.forEach(key -> System.out.println("IconFound: " + (UIManager.getIcon(key) != null) + "\tKey: " + key + suffix));
// Output / Test - single Key
System.out.println("\n");
String key = "FileView.directoryIcon"; // Copied from console
System.out.println("IconFound: " + (UIManager.getIcon(key) != null) + "\tKey: " + key + suffix);
}
}
【问题讨论】:
标签: java swing icons uimanager