在在SWING 的 JFileChooser如何俘获返回事件?
JFileChoose 可以为我们的开发 GUI界面带来很大的方便,在选择对话框时只需要使用就完事了。选择好文件后一般都需要做一些事情,比如说触发一些事件来做其他功能。事实上通过研读JFileChoose,我们拥有两种手段来激发选择文件后的事件。下面以例子加以说明。对于程序员来说,demo是最好的老师。只需要拷贝本例子就完全可以运行
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MyChoose extends JFrame {
private static final long serialVersionUID = 1L;
private JFileChooser jFileChooser = null;
private JButton jButton = null;
private JFileChooser getJFileChooser() {
if (jFileChooser == null) {
jFileChooser = new JFileChooser();
jFileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
//by linstener
jFileChooser.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
System.out.println("action Commmand:"+ e.getActionCommand());
if (e.getActionCommand().equals(JFileChooser.APPROVE_SELECTION))
{
System.out.println("select button action");//here call your function
}
else if (e.getActionCommand().equals(JFileChooser.CANCEL_SELECTION))
{
System.out.println("cancel button action");//here call your function
}
}
});
}
//by return result
/ /or use below function ,control your code
int result = jFileChooser.showOpenDialog(this);
System.out.println("Result......"+result);
if ( JFileChooser.CANCEL_OPTION ==result)
{
System.out.println(" FileChooser.CANCEL_OPTION..."+result);//here call your function
}
else if ( JFileChooser.APPROVE_OPTION ==result)
{
System.out.println(" JFileChooser.APPROVE_OPTION.."+result);//here call your function
}
else if ( JFileChooser.ERROR_OPTION ==result)
{
System.out.println(" JFileChooser.ERROR_OPTION..."+result);//here call your function
}
return jFileChooser;
}
/**
* This method initializes jButton
*
* @return javax.swing.JButton
*/
private JButton getJButton() {
if (jButton == null) {
jButton = new JButton("Open ChoiceDialog");
// jButton.setBounds(new Rectangle(15, 97, 34, 10));
jButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent e) {
getJFileChooser();
}
});
}
return jButton;
}
/**
* @param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MyChoose thisClass = new MyChoose();
thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
thisClass.setVisible(true);
}
});
}
/**
* This is the default constructor
*/
public MyChoose() {
super();
initialize();
}
/**
* This method initializes this
*
* @return void
*/
private void initialize() {
this.setSize(300, 200);
// this.setLayout(null);
// this.add(getJButton(), null);
this.setLayout( new BorderLayout() );
this.add("Center",getJButton());
}
}