使用jEditorPane 中的超链接 https://stackoverflow.com/questions/3693543/hyperlink-in-jeditorpane链接,我设法在 jEditorPane 中获取超链接。
但现在我想为超链接添加悬停效果。
我尝试使用 CSS 来应用
MyHTMLEditorKit kit = new MyHTMLEditorKit();
setEditorKitForContentType("text/html", kit);
addHyperlinkListener(createHyperlinkListener());
StyleSheet css= kit.getStyleSheet();
css.addRule("a { color: red;}");
where MyHTMlEditorKit
延伸HTMLEditorKit
。
我也尝试过遵循 CSS,但没有成功。
a:hover{color:red;}
另外,我尝试过onmouseover="this.style.color='red'"
超链接中的属性,但即使这样也不起作用。
那么我怎样才能实现onhover
jEditorPane 中的超链接效果如何?
这是我的版本,但似乎不是一个好的解决方案。所以我想看看是否有人有更干净的方法。
import java.awt.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.text.*;
import javax.swing.text.html.*;
public class HoverEffectTest {
private static final String SO = "http://stackoverflow.com/";
private final String s = "<a href='%s' color='%s'>%s</a><br>";
private final String s1 = String.format(s + "aaaaaaaaaaaaaa<br>", SO, "blue", SO);
private final String s2 = String.format(s + "cccc", SO, "#0000FF", "bbbbbbbbbbb");
private final JEditorPane editor = new JEditorPane(
"text/html", "<html>" + s1 + s2);
private JComponent makeUI() {
editor.setEditable(false);
//@see: BasicEditorPaneUI#propertyChange(PropertyChangeEvent evt) {
// if ("foreground".equals(name)) {
editor.putClientProperty(JEditorPane.HONOR_DISPLAY_PROPERTIES, Boolean.TRUE);
editor.addHyperlinkListener(new HyperlinkListener() {
@Override public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType() == HyperlinkEvent.EventType.ENTERED) {
setElementColor(e.getSourceElement(), "red");
} else if (e.getEventType() == HyperlinkEvent.EventType.EXITED) {
setElementColor(e.getSourceElement(), "blue");
} else if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
Toolkit.getDefaultToolkit().beep();
}
//I don't understand why this is necessary...
//??? call BasicTextUI#modelChanged() ???
editor.setForeground(Color.WHITE);
editor.setForeground(Color.BLACK);
}
});
return new JScrollPane(editor);
}
private void setElementColor(Element element, String color) {
AttributeSet attrs = element.getAttributes();
Object o = attrs.getAttribute(HTML.Tag.A);
if (o instanceof MutableAttributeSet) {
MutableAttributeSet a = (MutableAttributeSet) o;
a.addAttribute(HTML.Attribute.COLOR, color);
}
}
public static void main(String... args) {
EventQueue.invokeLater(new Runnable() {
@Override public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI() {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.getContentPane().add(new HoverEffectTest().makeUI());
f.setSize(320, 240);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)