JOptionPane 中 ArrayList 的可点击链接
Clickable links from ArrayList in JOptionPane
我正在尝试在我的 Browser class
(在 eclipse 中创建)中实现一个历史按钮,我希望按钮中的链接可以点击。这是我的代码,当用户按下按钮 History
:
时启动
private void showMessage() {
try {
String message = new String();
message = history.toString();
JOptionPane.showMessageDialog(null, message);
} catch (NullPointerException e) {
System.out.println("Something is wrong with your historylist!");
}
}
在上面的代码中,history
是一个包含之前访问过的所有网页的列表。
我试过使用这里介绍的方法:
clickable links in JOptionPane,我开始工作了。问题是,这个解决方案只允许我预定义 URL:s,但我希望显示我的列表 history
,并且其中的 URL 可以点击。
例如,如果我访问了 https://www.google.com and https://www.engadget.com,列表将如下所示:history = [www.google.com, www.engadget.com]
,并且两个链接都应该可以单独点击。
这是当有人按下 history
按钮时应该调用的函数。它使用 JEditorPane
和 HyperlinkListener
。下面代码中的字符串 html
添加了所需的 html 编码,以便 HyperlinkListener
可以阅读和访问网页。
public void historyAction() {
String html = new String();
for (String link : history) {
html = html + "<a href=\"" + link + "\">" + link + "</a>\n";
}
html = "<html><body" + html + "</body></html>";
JEditorPane ep = new JEditorPane("text/html", html);
ep.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
loadURL(e.getURL().toString());
}
}
});
ep.setEditable(false);
JOptionPane.showMessageDialog(null, ep);
}
我正在尝试在我的 Browser class
(在 eclipse 中创建)中实现一个历史按钮,我希望按钮中的链接可以点击。这是我的代码,当用户按下按钮 History
:
private void showMessage() {
try {
String message = new String();
message = history.toString();
JOptionPane.showMessageDialog(null, message);
} catch (NullPointerException e) {
System.out.println("Something is wrong with your historylist!");
}
}
在上面的代码中,history
是一个包含之前访问过的所有网页的列表。
我试过使用这里介绍的方法:
clickable links in JOptionPane,我开始工作了。问题是,这个解决方案只允许我预定义 URL:s,但我希望显示我的列表 history
,并且其中的 URL 可以点击。
例如,如果我访问了 https://www.google.com and https://www.engadget.com,列表将如下所示:history = [www.google.com, www.engadget.com]
,并且两个链接都应该可以单独点击。
这是当有人按下 history
按钮时应该调用的函数。它使用 JEditorPane
和 HyperlinkListener
。下面代码中的字符串 html
添加了所需的 html 编码,以便 HyperlinkListener
可以阅读和访问网页。
public void historyAction() {
String html = new String();
for (String link : history) {
html = html + "<a href=\"" + link + "\">" + link + "</a>\n";
}
html = "<html><body" + html + "</body></html>";
JEditorPane ep = new JEditorPane("text/html", html);
ep.addHyperlinkListener(new HyperlinkListener() {
public void hyperlinkUpdate(HyperlinkEvent e) {
if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) {
loadURL(e.getURL().toString());
}
}
});
ep.setEditable(false);
JOptionPane.showMessageDialog(null, ep);
}