简单/懒惰的答案是:当然不行。即使在一个纯html页面中,你需要一些javascript来实现这个功能。JEditorPane不能处理javascript(我认为,也许我错了),所以没有机会。
现在,你可以采用不同的方法:
- 更改一个字段(或创建一个新的字段)与链接。
- 链接将具有类似于“#rowXXX”的url,其中XXX是行号。
<a href="#row001">Some field</a>
- 在jEditorPane中添加
HyperlinkListener
:
editor.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
String rowcode = e.getDescription();
int row = Integer.parseInt(rowcode.replace("#row",""));
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
});
现在,在
row
中,您应该有行号。
完整示例
package test;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
public class App extends JFrame {
private static final long serialVersionUID = 1L;
private String HTML = "<html><table border=\"1\"><tr><td><a href=\"#row001\">First row</a></td></tr><tr><td><a href=\"#row002\">Second row</a></td></tr><tr><td><a href=\"#row003\">Third row</a></td></tr></table></html>";
private JPanel contentPane;
private JEditorPane editor;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
App frame = new App();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public App() {
setTitle("HTML TABLE CLICKABLE");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 408, 235);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
editor = new JEditorPane();
editor.setEditable(false);
editor.setContentType("text/html");
contentPane.add(editor, BorderLayout.CENTER);
editor.setText(HTML);
editor.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent e) {
if(e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
String rowcode = e.getDescription();
int row = Integer.parseInt(rowcode.replace("#row",""));
System.out.println(row);
}
}
});
}
}