我想在Java Swing JEditorPane
中启用HTML链接的键盘导航,这可能吗?
答案 0 :(得分:3)
是的,对于不可编辑的窗格,您需要将键绑定到InputMap中的"previous-link-action"
,"next-link-action"
和"activate-link-action"
HTMLEditorKit操作。这是一个代码示例:
import java.awt.BorderLayout;
import java.awt.HeadlessException;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;
import javax.swing.Action;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
public class Example {
public static void main(final String[] args) throws HeadlessException, InvocationTargetException, InterruptedException {
SwingUtilities.invokeAndWait(() -> {
final JFrame jFrame = new JFrame();
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setLayout(new BorderLayout());
final JEditorPane editor = new JEditorPane();
editor.setEditable(false);
editor.setFocusable(true);
editor.setContentType("text/html");
final HTMLDocument doc = (HTMLDocument) editor.getDocument();
final HTMLEditorKit editorKit = (HTMLEditorKit) editor.getEditorKit();
try {
doc.remove(0, doc.getLength());
editorKit.insertHTML(doc, 0, "<a href=\"http://google.com\">link one</a> and <a href=\"http://bing.com\">link two</a>", 0, 0, null);
editor.setCaretPosition(0);
} catch (final Exception e) {
e.printStackTrace();
}
final InputMap inputMap = editor.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
final KeyStroke nextKey = KeyStroke.getKeyStroke(KeyEvent.VK_PERIOD, InputEvent.CTRL_MASK);
final KeyStroke prevKey = KeyStroke.getKeyStroke(KeyEvent.VK_COMMA, InputEvent.CTRL_MASK);
final KeyStroke goKey = KeyStroke.getKeyStroke(KeyEvent.VK_G, InputEvent.CTRL_MASK);
final Action prevAction = editor.getActionMap().get("previous-link-action");
final Action nextAction = editor.getActionMap().get("next-link-action");
final Action goAction = editor.getActionMap().get("activate-link-action");
System.out.println("ks " + nextKey + " " + prevKey + " " + goKey);
System.out.println("ac: " + nextAction + " " + prevAction + " " + goAction);
inputMap.put(nextKey, "next-link-action");
inputMap.put(prevKey, "previous-link-action");
inputMap.put(goKey, "activate-link-action");
editor.addHyperlinkListener(e -> {
System.out.println(e.getURL());
});
jFrame.add(editor, BorderLayout.CENTER);
jFrame.setSize(400, 400);
jFrame.setVisible(true);
});
}
}