运行界面如下:
点击确定按钮后显示如下界面:
程序代码如下:
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileFilter;
import javax.swing.JFileChooser;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeExpansionListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
public class MyTree extends Frame implements
ActionListener
{ Button ok,cancel;
public MyTree()
{
//super("随机抽取");
this.setBounds(280,120,200,240);
this.setBackground(Color.lightGray);
this.setLayout(new FlowLayout(1));
ok=new Button("确定");
this.add(ok);
ok.addActionListener(this);
//在命令按钮上注册被实现的监听 cancel= new
Button("取消"); this.add(cancel);
cancel.addActionListener(this); //在命令按钮上注册被实现的监听
this.setVisible(true);
}
public void actionPerformed(ActionEvent
t) //实现按钮ActionListener监听器的唯一抽象方法,定义按钮单击时的行为
{ if(t.getSource()==ok)
//区分在哪个按钮上发生的ActionEvent事件
{ //初始化文件选择框
JFileChooser
fDialog = new JFileChooser();
//设置文件选择框的标题
fDialog.setDialogTitle("请选择所要打开的文件");
//弹出选择框
int returnVal
= fDialog.showOpenDialog(null);
//
如果是选择了文件
if(JFileChooser.APPROVE_OPTION
== returnVal){
//打印出文件的路径,你可以修改位 把路径值 写到 textField 中
System.out.println(fDialog.getSelectedFile());
}
}
else System.exit(0);
}
FileFilter filterDirectory = new FileFilter()
{
public boolean accept(File
pathname) {
return
pathname.isDirectory();
}
};
FileFilter filterFile = new
FileFilter() {
public boolean accept(File
pathname) {
return
pathname.isFile();
}
};
public static void main(String
args[]) {
new
MyTree();
}
}