我遇到了一个问题,不知道如何使用HTML设置JList选定文本的颜色。
我使用Java Swing和HTML,已经成功地为JList中每个字符串的特定部分设置了颜色,我的示例如下所示:
这样很理想,因为我可以为每个条目设置任意数量的不同颜色!
然而,当选择文本时,只有默认的黑色文本变成白色!html着色的文本保持其颜色,而不是也变成白色,这导致某些颜色的文本非常难读:
我该如何在选定时设置文本的颜色?
我尝试在JList上使用setSelectionForeground(Color.WHITE)方法,但它没有影响到html着色的文本(虽然它确实影响了非html着色的文本)。
我还阅读了Oracle的HTML-in-Swing教程(我最初发现了HTML着色),但找不到解决方案。
以下是我简短示例的代码:
我使用Java Swing和HTML,已经成功地为JList中每个字符串的特定部分设置了颜色,我的示例如下所示:
这样很理想,因为我可以为每个条目设置任意数量的不同颜色!
然而,当选择文本时,只有默认的黑色文本变成白色!html着色的文本保持其颜色,而不是也变成白色,这导致某些颜色的文本非常难读:
我该如何在选定时设置文本的颜色?
我尝试在JList上使用setSelectionForeground(Color.WHITE)方法,但它没有影响到html着色的文本(虽然它确实影响了非html着色的文本)。
我还阅读了Oracle的HTML-in-Swing教程(我最初发现了HTML着色),但找不到解决方案。
以下是我简短示例的代码:
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.UIManager;
import java.awt.Color;
public class JListSelectionColorTest extends JFrame {
private String[] exampleText = {"Some example text without any color changes",
"Some more example text without color changes",
"Even more plain text!",
"<html>Uncolored Text! <font color=orange>Now some example Text with color!</font> more Uncolored Text!</html>",
"<html>Uncolored Text! <font color=green>And some more example text with color! Text, Text, Text!</font> more Uncolored Text!</html>",
"<html>Uncolored Text! <font color=red>A string with red color, Text Text Text!</font> more Uncolored Text!</html>",
"<html>Uncolored Text! <font color=blue>And finally a string with blue color, Text Text Text!</font> more Uncolored Text!</html>",
"<html>Uncolored Text! <font color=purple><selection color=white>Testing if some html can turn the selection color white!</selection></font> more Uncolored Text!</html>"};
public JListSelectionColorTest() {
super("JList Selection Color Test");
// Set the Look and Feel of the window to the Native System's Look and Feel
// (When using the default Look and Feel the problem still persists!)
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// Create a JList of Strings containing the exampleText String array
JList<String> exampleJList = new JList<String>(exampleText);
// Set the JList's text selection color to white
exampleJList.setSelectionForeground(Color.WHITE); // This doesn't seem to affect the html-colored text's selection foreground
// Add the JList to the JFrame
add(exampleJList);
pack();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String[] args) {
new JListSelectionColorTest();
}
}