本例展示如何在 JApplet 中使用 Swing 的 JTree 組件實現樹形結構導航,支持從外部配置文件動態構建樹節點,並實現節點點擊跳轉網頁功能。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.io.*;
import java.net.*;
import java.util.*;
import java.applet.*;
public class PageTree extends JApplet implements TreeSelectionListener {
DefaultMutableTreeNode[] nodeAt = new DefaultMutableTreeNode[256];
String target = null;
Hashtable links = new Hashtable(); // 節點 -> URL 映射
AppletContext context;
public void init() {
context = getAppletContext();
DefaultMutableTreeNode root = null;
getContentPane().setLayout(new BorderLayout());
// 從參數獲取配置文件路徑
String s = getParameter("file");
if (s != null) {
try {
URL url = new URL(getDocumentBase(), s);
BufferedReader br = new BufferedReader(
new InputStreamReader(url.openStream(), "JISAutoDetect"));
String line = br.readLine();
if (line == null) return;
root = new DefaultMutableTreeNode(line);
nodeAt[0] = root;
int level = 0;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, "|");
String token = st.nextToken();
int n = countSpaces(token); // 根據縮進空格數確定層級
DefaultMutableTreeNode node = new DefaultMutableTreeNode(token.trim());
// 處理層級跳轉,補充空節點
for (int i = level + 1; i < n; i++) {
DefaultMutableTreeNode dummy = new DefaultMutableTreeNode("");
nodeAt[i].add(dummy);
nodeAt[i+1] = dummy;
}
level = n;
nodeAt[n].add(node);
nodeAt[n+1] = node;
// 處理 "|" 後的 URL 映射
if (st.hasMoreTokens()) {
token = st.nextToken();
try {
url = new URL(token.trim());
links.put(node, url);
} catch (MalformedURLException ex) { ex.printStackTrace(); }
}
}
} catch (MalformedURLException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
}
s = getParameter("target");
if (s != null) target = s.trim();
JTree tree = new JTree(root);
tree.addTreeSelectionListener(this);
JScrollPane jsp = new JScrollPane(tree);
getContentPane().add(jsp, BorderLayout.CENTER);
}
private int countSpaces(String s) {
int n = 0;
while (s.charAt(n) == ' ') { n++; }
return n;
}
public void valueChanged(TreeSelectionEvent e) {
TreePath path = e.getPath();
Object o = path.getLastPathComponent();
URL url = (URL) links.get(o);
if (url != null) {
System.out.println(links.get(o));
context.showDocument(url); // 通知瀏覽器打開鏈接
}
}
}
根節點 子節點1|https://example.com/page1.html 孫節點1.1|https://example.com/page1_1.html 子節點2|https://example.com/page2.html
規則:
<applet code="PageTree.class" width="300" height="400"> <param name="file" value="treeconfig.txt"> <param name="target" value="_blank"> </applet>
DefaultMutableTreeNode 樹Hashtable 存儲節點對象與 URL 的關聯TreeSelectionListener,valueChanged() 中獲取節點對應 URLAppletContext.showDocument(URL) 通知瀏覽器打開新頁面InputStreamReader(url.openStream(), "JISAutoDetect") 自動檢測日文編碼Swing Applet 已過時。現代 Web 樹形導航請使用:JavaScript 樹組件(如 zTree、jstree、Element UI Tree、Ant Design Tree)配合 JSON 數據源,支援懶加載、搜索、拖拽、複選等豐富交互。