//LeftPanel.java
package com.jungleford.test;
import java.awt.BorderLayout;
import javax.swing.*;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import java.util.Observable;
import java.util.Observer;
public final class LeftPanel extends JPanel
{// 把树型选择视图布局在左边
private JTree tree;// 树型选择视图
private JScrollPane scroll;// 让视图可滚动
private DefaultMutableTreeNode root, node1, node2;// 根节点及两个叶子
private Sensor sensor;// sensor是一个Observable,由于只能单根继承,所以作为组合成员
private String file;// 图片文件名,与RightPanel通信的内容
public LeftPanel(Observer observer)
{
file = "";
sensor = new Sensor();
sensor.addObserver(observer);// 向Observable注册Observer
root = new DefaultMutableTreeNode("Images");
tree = new JTree(root);
node1 = new DefaultMutableTreeNode("Rabbit");
node2 = new DefaultMutableTreeNode("Devastator");
root.add(node1);
root.add(node2);
tree.addTreeSelectionListener(new TreeSelectionListener()
{// 树节点选择动作
public void valueChanged(TreeSelectionEvent e)
{
Object obj = e.getPath().getLastPathComponent();
if (obj instanceof DefaultMutableTreeNode)
{
DefaultMutableTreeNode node = (DefaultMutableTreeNode)obj;
if (node == root)
file = "";// 选择根
if (node == node1)
file = "rabbit.jpg";// 选择node1
if (node == node2)
file = "devastator.gif";// 选择node2
sensor.setData(file);// 改变Observable
sensor.notifyObservers();// 通知observer,对象已改变
}
}
});
scroll = new JScrollPane(tree);
add(scroll, BorderLayout.CENTER);
}
public Observable getSensor()
{// 返回Observable对象,使Observer可以获取
return sensor;
}
}
class Sensor extends Observable
{// 定义自己的Observable
private Object data;
public void setData(Object newData)
{
data = newData;
setChanged();// 改变Observable
System.out.println("Data changed!");
}
public Object getData()
{
return data;
}
}