首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

JFileChooser怎么保存特定的文件类型

2012-01-11 
JFileChooser如何保存特定的文件类型啊我想用JFileChooser保存特定的文件类型,如果保存的不是指定的文件类

JFileChooser如何保存特定的文件类型啊
我想用JFileChooser保存特定的文件类型,如果保存的不是指定的文件类型,则弹出一个JDialog,但我实在不会写了..请各位大侠帮忙啊..我的源代码是..
package gui;

import java.io.File;


import javax.swing.filechooser.FileFilter;

public class MyFilter extends FileFilter{
  private String extenssion;
   

  public MyFilter(String extenssion){
  this.extenssion = extenssion;
  }
@Override
public boolean accept(File file) {
if(file.getName().endsWith(extenssion)){
return true;
}else return false;
}

@Override
public String getDescription() {

  return null;
}

}






package gui;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;

public class Demo4 extends JFrame implements ActionListener {
private JButton closeButton, openButton, saveButton;
private JDialog dia;
private JFileChooser chooser;
private FileFilter filter;

public Demo4() {
this.setLayout(new FlowLayout());
this.setSize(800, 800);
closeButton = new JButton("关闭");
openButton = new JButton("打开");
saveButton = new JButton("保存");
closeButton.addActionListener(this);
openButton.addActionListener(this);
saveButton.addActionListener(this);

dia = new JDialog(this);
dia.setSize(400, 400);
dia.add(closeButton);

this.add(openButton);
this.add(saveButton);
chooser = new JFileChooser();

}
   
public void actionPerformed(ActionEvent e) {
chooser = new JFileChooser();
String name = e.getActionCommand();
if (name.equals("打开")) {

chooser.showOpenDialog(this);
} else if (name.equals("保存")) {

chooser.addChoosableFileFilter(new MyFilter(".xls"));
chooser.showSaveDialog(this);


}
}


public static void main(String[] args) {
new Demo4().setVisible(true);
}
}


[解决办法]
代码太乱了..选择的时候是要先创建你要保存文件的类型..下面.我自己写了两个功能差不多的..楼主请看下:

Java code
import java.awt.*;import java.awt.event.*;import javax.swing.*;import javax.swing.event.*;import javax.swing.filechooser.FileFilter;import javax.swing.text.DefaultStyledDocument;import javax.swing.text.Document;import javax.swing.text.StyledDocument;import java.io.*;import java.util.HashMap;import java.util.Map;import java.util.regex.Matcher;import java.util.regex.Pattern;public class TestFileDialog {        public static void main(String[] args) {        new FileDialog();    }}class FileDialog {    private File currentFile =null;    public  static JTextPane display;    private JFrame frame=new JFrame("File");    private JButton openButton,deleteButton,redoButton,saveButton;    private Container container=frame.getContentPane();    private JPanel panel;    private boolean change;    private JScrollPane scroll;    private JMenuBar menuBar;    private JMenu fileMenu=new JMenu("文件");    private JLabel statusBar = new JLabel();    private JToolBar toolBar = new JToolBar();    private JMenuItem fileMenuItem,openMenuItem,exitMenuItem;    private StyledDocument styledDoc=new DefaultStyledDocument();    private Document doc;    private static Map<String,ImageIcon> iconsMap = new HashMap<String,ImageIcon>();    private static ImageIcon[] icons = null;        static {        icons =new ImageIcon[]{                new ImageIcon(TestFileDialog.class.getClassLoader().getResource("images/save.gif")),                new ImageIcon(TestFileDialog.class.getClassLoader().getResource("images/open.gif")),                new ImageIcon(TestFileDialog.class.getClassLoader().getResource("images/title.gif"))        };        iconsMap.put("open", icons[1]);        iconsMap.put("save",icons[0]);        iconsMap.put("title",icons[2]);    }        public FileDialog() {        /*        try{            UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");                    }catch(Exception e){            e.printStackTrace();        }         */        frame.setSize(800,600);        frame.setLocation(400,100);        frame.setIconImage(Toolkit.getDefaultToolkit().getImage(TestFileDialog.class.getClassLoader().getResource("images/title.gif")));                        openButton =new JButton("打开",icons[1]);        //redoButton =new JButton("RedoButton");        saveButton =new JButton("保存",icons[0]);                menuBar =new JMenuBar();        menuBar.add(fileMenu);        fileMenuItem = new JMenuItem("保存");        openMenuItem = new JMenuItem("打开");        exitMenuItem = new JMenuItem("退出");        fileMenu.add(openMenuItem);        fileMenu.add(fileMenuItem);        fileMenu.addSeparator();        fileMenu.add(exitMenuItem);                display= new JTextPane(styledDoc);        styledDoc.addDocumentListener(new documentLis());//        doc=display.getDocument();        display.setFont(new Font("宋体", Font.PLAIN, 20));                container.setLayout(new BorderLayout());        container.add(display,"Center");        toolBar.add(saveButton);        toolBar.addSeparator();        container.add(statusBar,"South");        toolBar.add(openButton);        container.add(toolBar,"North");                scroll = new JScrollPane(display);        container.add(scroll);        frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);        frame.addWindowListener(new WindowAdapter(){            public void windowClosing (WindowEvent e) {                System.exit(0);            }        });                        frame.setJMenuBar(menuBar);        frame.setVisible(true);                //事件管理驱动        ActionListener file = new fileAction();                //添加事件        exitMenuItem.addActionListener(file);        openMenuItem.addActionListener(file);        saveButton.addActionListener(file);        fileMenuItem.addActionListener(file);        openButton.addActionListener(file);                } 


[解决办法]
接着上面的..

Java code
 
public class documentLis implements DocumentListener{
    public void changedUpdate(DocumentEvent arg0) {     
      change=true;         
    }
    public void insertUpdate(DocumentEvent arg0) {     
      change=true;
    }
    public void removeUpdate(DocumentEvent arg0) {     
      change=true;     
    }   
  }

class fileAction implements ActionListener {

public void actionPerformed(ActionEvent e) {
String command =e.getActionCommand();
if(command=="保存"){
saveFile();
}else if(command=="打开"){
openFile();
}else if(command=="退出"){
exitText();
}

}

}

public void exitText(){
String path="无标题";
if(currentFile!=null){
int num = JOptionPane.showConfirmDialog(container,"文件"+path+"内容已经改变,是否保存文件?","文字编辑",JOptionPane.YES_NO_CANCEL_OPTION,JOptionPane.WARNING_MESSAGE);
if(num==0){
saveAsFile();
}else if(num==1){
System.exit(0);
}else if(num==1) {
openFile();
}
}
//System.exit(0);
}

public void openFile(){
JFileChooser open = new JFileChooser();
open.addChoosableFileFilter(new JavaFileFilter());
open.addChoosableFileFilter(new TxtFileFilter());
open.addChoosableFileFilter(new JpgFileFilter());
open.addChoosableFileFilter(new DocFileFilter());
int state = open.showOpenDialog(frame);
File file = open.getSelectedFile();

if(file!=null && state == JFileChooser.APPROVE_OPTION){
currentFile=file;
display.setText("");
frame.setTitle(file.getName()+"文字编辑");
try {
FileReader readFile =new FileReader(file.getAbsoluteFile());
int len =(int)file.length();
char[]buffer=new char[len];
readFile.read(buffer,0,len);
display.setText(new String(buffer));
readFile.close();

}catch(IOException e) {
e.printStackTrace();
}
change=false;
}
}

public void saveFile(){      //保存
    if (currentFile != null){
      try{
        FileWriter file = new FileWriter(currentFile);
        file.write(display.getText());
        file.close();
      }catch(Exception e){ }
      change=false;
    }else  saveAsFile();
  }

  public void saveAsFile() {      //另存为
    JFileChooser save=new  JFileChooser();
    save.addChoosableFileFilter(new JavaFileFilter());
    save.addChoosableFileFilter(new TxtFileFilter());
    save.setDialogTitle("另存为");
    int state = save.showSaveDialog(frame);
    File file=save.getSelectedFile();           
    if (file != null && state == JFileChooser.APPROVE_OPTION){ 
      /**正则表达式用来查看输入的文件名是否有后缀名 */
    Pattern pattern=Pattern.compile(".*\\.[a-z]+",Pattern.CASE_INSENSITIVE);   
    Matcher matcher = pattern.matcher(file.getAbsolutePath());


    if(!matcher.find()){     
    file=new File(file.getAbsolutePath().concat(".txt"));
    }   
    currentFile=file;         
    try {
      FileWriter target = new FileWriter(currentFile.getAbsolutePath());
      target.write(display.getText());
      frame.setTitle(currentFile.getName()+ " - 文字编辑");
      target.close();
    } catch (Exception e) { }
    change=false;
    }   
  }

 
  class JavaFileFilter extends FileFilter {
  public String getDescription() {
    return "java源文件(*.java)";
  }
  public boolean accept(File file) {
    return file.getName().toLowerCase().endsWith(".java");
  }
}
class TxtFileFilter extends FileFilter {
  public String getDescription() {
    return "文本文档(*.txt)";
  }
  public boolean accept(File file) {
    return file.getName().toLowerCase().endsWith(".txt");
  }

}

class JpgFileFilter extends FileFilter {
public boolean accept(File file) {
return file.getName().toLowerCase().endsWith(".jpg");
}
public String getDescription() {
return "文本文档(*.jpg)";
}

}

class DocFileFilter extends FileFilter {
public boolean accept(File file) {
return file.getName().toLowerCase().endsWith(".doc");
}
public String getDescription() {
return "Doc文档(*.doc)";
}

}
}


热点排行