JAVA实现无限级水果分类
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
import java.util.*;
import javax.swing.event.*;
import java.io.*;
//主框架类
public class Fruit extends javax.swing.JFrame
{
public Fruit()
{
JFrame f = new JFrame("水果");
String[] s1 = {"西瓜","西红柿","椰子","香蕉"};
String[] s2 = {"草莓","梨","青苹果"};
String[] s3 = {"黑枣","榴莲"};
String[] s4 = {"番石榴","桔子","荔枝","葡萄","桃子"};
Hashtable hashtable1 = new Hashtable();
hashtable1.put("寒性水果",s1);
hashtable1.put("凉性水果",s2);
hashtable1.put("热性水果",s3);
hashtable1.put("温性水果",s4);
//用hashtable方法构建树形结构
tree1 = new JTree(hashtable1);
//设置树结点响应监听事件
tree1.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
valueChange1(evt);
}
});
//用JScrollPane实现Tree结构的可拉伸扩展
scrollPane1=new JScrollPane(tree1);
Container contentPane = f.getContentPane();
//label1显示图片
www.751com.cn
scrollPane2 = new JScrollPane(editorPane);
//设置editorPane是不可修改的
editorPane.setEditable(false);
/**以splitPane2中包含splitPane1,再用splitPane1包含label1和scrollPane2的内容
**实现界面三分的结构**/
//设置splitPane1是垂直分布,并且是不可再分的,包含label1和scrollPane2
splitPane1 = new JSplitPane(JSplitPane.VERTICAL_SPLIT,false,label1,scrollPane2);
splitPane1.setDividerLocation(200);
splitPane1.setOneTouchExpandable(false);
splitPane1.setDividerSize(10);
//设置splitPane2是水平分布,是可再分的,包含scrollPane1和splitPane1
splitPane2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,true,scrollPane1,splitPane1);
splitPane2.setDividerLocation(130);
splitPane2.setOneTouchExpandable(false);
splitPane2.setDividerSize(5);
contentPane.add(splitPane2);
f.setSize(400,500);//设置容器大小
f.show();
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
/**用valueChange1实现对结点事件的响应,将棋实例化
**/
private void valueChange1(javax.swing.event.TreeSelectionEvent evt) {
DefaultMutableTreeNode selectionNode=(DefaultMutableTreeNode)tree1.getLastSelectedPathComponent();
//显示图片
try{
String nodename=selectionNode.toString();
label1.setIcon(new ImageIcon("pic/"+nodename+".jpg"));
System.out.println(nodename+".jpg");
String filepath = "file:"+System.getProperty("user.dir") +System.getProperty("file.separator") +
nodename+".txt";
//显示文本到editorPane
try {
editorPane.setPage(filepath);
} catch(IOException ex) {
System.out.println("找不到此文件");
}
}
catch(NullPointerException exc){}
}
//主函数
public static void main(String[] arg)
{
new Fruit();
}
//变量声名
private javax.swing.JLabel label1;
private javax.swing.JPanel panel1;
private javax.swing.JSplitPane splitPane1,splitPane2;
private javax.swing.JScrollPane scrollPane1,scrollPane2,scrollPane3;
private javax.swing.JTree tree1;
private javax.swing.JEditorPane editorPane;
}516