[JAVA100例]076、在Applet中操纵Swing[Java编程]
本文“[JAVA100例]076、在Applet中操纵Swing[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
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);
}
}
}
以上是“[JAVA100例]076、在Applet中操纵Swing[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |