《Java2图形设计卷II:Swing》配套光盘源码
源代码在线查看: test.java
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;
public class Test extends JFrame {
public Test() {
JTree tree = new JTree();
getContentPane().add(tree);
tree.addTreeWillExpandListener(
new TreeWillExpandListener() {
public void treeWillExpand(TreeExpansionEvent e)
throws ExpandVetoException {
TreePath path = e.getPath();
TreeNode node = (TreeNode)
path.getLastPathComponent();
if(node.toString().equals("colors")) {
JOptionPane.showMessageDialog(Test.this,
"Can't Expand Colors",
"Expansion Vetoed",
JOptionPane.INFORMATION_MESSAGE);
throw new ExpandVetoException(e);
}
}
public void treeWillCollapse(TreeExpansionEvent e)
throws ExpandVetoException {
TreePath path = e.getPath();
TreeNode node = (TreeNode)
path.getLastPathComponent();
if(node.toString().equals("food")) {
JOptionPane.showMessageDialog(Test.this,
"Can't Collapse Food",
"Collapse Vetoed",
JOptionPane.INFORMATION_MESSAGE);
throw new ExpandVetoException(e);
}
}
});
}
public static void main(String args[]) {
GraphicJavaApplication.launch(new Test(),
"Vetoing Node Expansion/Collapse",300,300,300,200);
}
}
class GraphicJavaApplication extends WindowAdapter {
public static void launch(final JFrame f, String title,
final int x, final int y,
final int w, int h) {
f.setTitle(title);
f.setBounds(x,y,w,h);
f.setVisible(true);
f.setDefaultCloseOperation(
WindowConstants.DISPOSE_ON_CLOSE);
f.addWindowListener(new WindowAdapter() {
public void windowClosed(WindowEvent e) {
System.exit(0);
}
});
}
}