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.*;
/**
* <p>Title: Applet中使用SWING</p>
* <p>Description: 使用SWING的JApplet實現樹功能。</p>
* <p>Copyright: Copyright (c) 2003</p>
* <p>Filename: PageTree.java</p>
* @version 1.0
*/
public class PageTree extends JApplet implements TreeSelectionListener {
DefaultMutableTreeNode[] nodeAt = new DefaultMutableTreeNode[256];
String target = null;
Hashtable links = new Hashtable();
AppletContext context;
public void init() {
//獲取Applet的內容
context = getAppletContext();
//定義根節點
DefaultMutableTreeNode root = null;
getContentPane().setLayout(new BorderLayout());
//獲取參數。定義的數據配置文件。
String s = getParameter("file");
if (s != null) {
try {
//使用URL方式打開數據文件,實現在網絡上使用。
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;
//對“|”符號後的數據進行處理
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);
}
}
/**
*<br>方法說明:計算空格數
*<br>輸入參數:
*<br>返回類型:
*/
private int countSpaces(String s) {
int n = 0;
while (s.charAt(n) == ´ ´) {
n++;
}
return n;
}
/**
*<br>方法說明:樹選擇監聽實現方法
*<br>輸入參數:TreeSelectionEvent e 選擇樹節點事件
*<br>返回類型:
*/
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));
//打開連接,通知浏覽器加載網頁(使用浏覽器打開Applet的情況下)
context.showDocument(url);
}
}
}