Reputation: 2963
Swing allows html in components like JLabel
. This document talks about this in detail. It also shows how the color of a specific text could be changed.
I am working with an existing swing application with thousands of such components. I want to change the color of the link where ever it is used. Doing them one at a time would be very tedious. By default if a color is not specified swing seems to render them as blue.
How can I change this default to something else ?
Upvotes: 5
Views: 1215
Reputation: 347214
So, after much digging through code I've learnt...
HTMLEditorKit
and associated APIsHTMLEditorKit
is maintain centrally/globally within the AppContext...From HTMLEditorKit#getStyleSheet
AppContext appContext = AppContext.getAppContext();
StyleSheet defaultStyles = (StyleSheet) appContext.get(DEFAULT_STYLES_KEY);
This is kind of important as it means, you don't spend a lot of time running about trying to look at the label's look and feel code AND you should be able to change the global style sheet in a single place and affect how everything gets rendered...this may be a good and a bad thing...
The next problem is, you can't actually access the StyleSheet
within the AppContext
as the DEFAULT_STYLES_KEY
is a private static final Object
...
This means you have to create an instance HTMLEditorKit
and use getStyleSheet
to get a reference to it...
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import sun.awt.AppContext;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
HTMLEditorKit kit = new HTMLEditorKit();
StyleSheet styleSheet = kit.getStyleSheet();
styleSheet.addRule("a {color:#ff0000;}");
JLabel label = new JLabel("<html><a href=http://stackoverflow.com/questions/tagged/java>Stackoverflow</a></html>");
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(label);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
Upvotes: 6