FileDialog filter

Hi
I'm using dialog boxes for Open and Save in my progra. Question is: Is it possible just to filter for java and text files.. heres my code.
fd2=new FileDialog(this,"Save As..",FileDialog.SAVE);
fd1=new FileDialog(this,"Open..",FileDialog.LOAD);
Open.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent ae2 )
txtmsg="";
fd1.setVisible(true);
String filename=fd1.getFile();
String dirname=fd1.getDirectory();
File openfile=new File(dirname,filename);
try
FileInputStream fis=new FileInputStream(openfile);
int bytelength=fis.available();//calculates the file size
for (int bytecount=0;bytecount<bytelength;bytecount++)
char fch=(char)fis.read();
txtmsg=txtmsg+fch;
ta.setText(txtmsg);
catch(Exception ioe)
System.out.println("An exception has occured");
);

yes it is possible
doublle click JAVA_HOME\demo\jc\swingset2\swingset2.jar (its long to start, be patient)
for source code look in JAVA_HOME\demo\jc\swingset2\src\*.java
marvinrouge

Similar Messages

  • How to open Excel FIles

    I am a novice
    When I open excel file  I found some problems.
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Reflection;
    using System.Windows.Forms;
    using XLS=Microsoft.Office.Interop.Excel;
    using WD=Microsoft.Office.Interop.Word;
    using Microsoft.Office.Core;
    namespace ExcelDataFillWord
        public partial class Form1 : Form
            public Form1()
                InitializeComponent();
            private void button1_Click(object sender, EventArgs e)
                //  Scheduler sched = new Scheduler();
                //foreach (Task t in sched.Tasks)
                //    Console.WriteLine(t.ToString());
                //    foreach (Trigger tr in t.Triggers)
                //        Console.WriteLine(tr.ToString());
            private void label1_Click(object sender, EventArgs e)
                FileDialog.Filter = "excel文件|*.xls|Excel文件|*.xlsx";
                FileDialog.Multiselect = false;
                FileDialog.Title = "打开excel文件";
                if (FileDialog.ShowDialog() == DialogResult.OK)
                    textBox1.Text = FileDialog.FileName;
                    object missing = System.Reflection.Missing.Value;
                    //object missing = Type.Missing;
                    CloseProcess();
                   //'Excel::Application excel =new Excel::ApplicationClass();
                    Microsoft.Office.Interop.Excel.Application excel= new Microsoft.Office.Interop.Excel.Application();
                    //Excel::Workbook  Wk =(Excel::Workbook )Xls.Workbooks.Open(textBox1.Text, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing,
    missing, missing, missing, missing);
                    Microsoft.Office.Interop.Excel.Workbook workbook =(Microsoft.Office.Interop.Excel.Workbook) excel.Application.Workbooks.Open(textBox1.Text , missing, missing, missing,
    missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                    //comboBox1.Items.Clear();
                    //foreach (Excel::Worksheet Sh in Wk.Worksheets)
                    //    comboBox1.Items.Add((Sh.Name).ToString());
                    workbook.Close(missing, missing, missing);
                    excel.Quit();
            private void CloseProcess()
                System.Diagnostics.Process[] excelProcess = System.Diagnostics.Process.GetProcessesByName("EXCEL");//实例化进程对象
                foreach (System.Diagnostics.Process p in excelProcess)
                    p.Kill();//关闭进程
                System.Threading.Thread.Sleep(10);//使线程休眠10毫秒
    problem is : can't change  excel.applicaitonclass's Com object   to   interface
    so I want to ask a question:
    excel.application is a interface ,then interface variant = a class( it inherients this interface)  object
    but interface is a abstract object ,It has no construct function . why We use  Excel.Applcation xsl=new Excel.Application();

    Hello,
    Perhaps this will help. Open an Excel file, select a sheet, range then set a value, save then close. The idea here is not to write or save but demo a few basic operations.
    Also note 'as is' all memory is cleaned up without resorting to what many do, force the garbage collector. This is important if objects are not cleaned up it is very possible in extreme cases to bring a machine down so one should ensure all objects are cleaned
    up which only comes from well written code be it C# or VB.NET
    using System;
    using System.Data;
    using System.Data.OleDb;
    using System.Runtime.InteropServices;
    using System.Windows.Forms;
    using Excel = Microsoft.Office.Interop.Excel;
    namespace Example_C1
    public partial class Form1 : Form
    public Form1()
    InitializeComponent();
    public void OpenExcelExample(string FileName, string SheetName)
    if (System.IO.File.Exists(FileName))
    bool Proceed = false;
    Excel.Application xlApp = null;
    Excel.Workbooks xlWorkBooks = null;
    Excel.Workbook xlWorkBook = null;
    Excel.Worksheet xlWorkSheet = null;
    Excel.Sheets xlWorkSheets = null;
    Excel.Range xlCells = null;
    xlApp = new Excel.Application();
    xlApp.DisplayAlerts = false;
    xlWorkBooks = xlApp.Workbooks;
    xlWorkBook = xlWorkBooks.Open(FileName);
    xlApp.Visible = false;
    xlWorkSheets = xlWorkBook.Sheets;
    for (int x = 1; x <= xlWorkSheets.Count; x++)
    xlWorkSheet = (Excel.Worksheet)xlWorkSheets.get_Item(x);
    if (xlWorkSheet.Name == SheetName)
    Proceed = true;
    break;
    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet);
    xlWorkSheet = null;
    if (Proceed)
    Excel.Range xlRange1 = null;
    xlRange1 = xlWorkSheet.get_Range("A1");
    xlRange1.Value = "Hello";
    Marshal.FinalReleaseComObject(xlRange1);
    xlRange1 = null;
    xlWorkSheet.SaveAs(FileName);
    else
    MessageBox.Show(SheetName + " not found.");
    xlWorkBook.Close();
    xlApp.UserControl = true;
    xlApp.Quit();
    ReleaseComObject(xlCells);
    ReleaseComObject(xlWorkSheets);
    ReleaseComObject(xlWorkSheet);
    ReleaseComObject(xlWorkBook);
    ReleaseComObject(xlWorkBooks);
    ReleaseComObject(xlApp);
    MessageBox.Show("Done");
    else
    MessageBox.Show("'" + FileName + "' not located. Try one of the write examples first.");
    private void ReleaseComObject(object obj)
    try
    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
    obj = null;
    catch (Exception)
    obj = null;
    private void button1_Click(object sender, EventArgs e)
    OpenExcelExample(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WS1.xlsx"), "Sheet3");
    private void releaseObject(object obj)
    try
    if (obj == null)
    System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
    obj = null;
    catch (Exception ex)
    obj = null;
    MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
    finally
    GC.Collect();
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem.

  • FileDialog, not JFileChooser, how to set filter? help+help!

    i want to add file filter to the bottom combo box control of FileDialog, but i have no idea.
    1. setFile("*.txt;*.java;") works in a silly style
    2. FilenameFilter doesn't work (return true or false makes no diff from accept function.
    if you used FileDialog before or saw some examples which work well, please give me a hand.
    please don't guess if u never use before.
    many thanks

    setFileNameFilter do not work for Windows 95, 98, or NT 4.0. So better use JFileChooser

  • FileDialog, how to set filter?

    i try to use
    setFilenameFilter(FilenameFilter filter)
    to set filter for FileDialog, but FilenameFilter is an interface, what is the story?
    do u know how to set filter?
    thanks in advance

    Construct a FileFilter class like:
    public class CustomFilter implements FileFilter{
         public CustomFilter(){
    public String getFileExtension(File file) {
    String ext = null;
    String s = file.getName();
    int i = s.lastIndexOf(".") + 1;
    ext = s.substring(i).toLowerCase();
    return ext;
    public String doSomething(){
    //do Something
    //return something
    and use the setFileFilter(FileFilter filter) method.

  • FileDialog....filter help!

    I'm still utterly confused as to how a FilenameFilter works for a filedialog...can anyone give me any sample code? I tried the following:
    fileDialog.setFilenameFilter(new java.io.FilenameFilter() {
                public boolean accept(File pathname) {
                    if (pathname.getName().endsWith(".ars")) {
                        return true;
                    else {
                        return false;
            });and got this error:
    <anonymous windowResults$6> is not abstract and does not override abstract method accept(java.io.File,java.lang.String) in java.io.FilenameFilterwindowResults being the class this is all in.

    java.io.FilenameFilter accept method takes two parameters a File object and a String. Use it with a java.awt.FileDialog. A javax.swing.filechooser.FileFilter's accept method takes a single String parameter and is used with a javax.swing.JFileChooser.
    Hope that helps
    DB

  • Displaying only folders in FileDialog

    I would like to create a dialog box that would allow the user to
    choose a directory, not a file. Is there any way to use the FileDialog box available in AWT to do this (and using Swing is not an option and i know how to do it in JFileChooser)??
    Any ideas or samples to how to do this would be greatly appreciated!

    I have not tested if this works, but you can try using the directory filter below via FileDialog's setFilenameFilter method.
    public class DirectoryFilter implements java.io.FilenameFilter {
    public void accept(File dir, String name) {
    File file = new File(dir, name);
    return file.isDirectory();

  • File Filter in AWT

    The FileDialog class in AWT does not include a file filter! The FileFilter class doesn't work properly, I tried using it in different ways, but it doesn't filter the files.
    How can this be achieved?
    TECHNOSAM.

    Using setFile("*.txt") works, but it has limitations.
    Once some file is clicked, the Filter effect is lost. There has to be some why by implementing the FilenameFilter interface. It's accept method can be implemented. I tried this method, but doesn't work. Or there could be some mistake in the way I have done it. This is the way i have done it:
    class MyFilter implements FilenameFilter
    public MyFilter() {}          
    public boolean accept(File dir,String name)
    if(name.endsWith("gif") || name.endsWith("jpg"))
    return true;
    return false;
    FileDialog fd = new FileDialog(parent,"File Open...");
    MyFilter f = new MyFilter();
    fd.setFilenameFilter(f);
    Is this alright? This does no good. Does somebody have a solution to this problem?
    Thanks,
    TechnoSam.

  • File Filtering in FileDialog on Windows

    We have a Java application that we are deploying primarily on Windows platforms. We use FileDialog to perform a "file save as" function. We would like to filter the list of files shown to match a file extension. Even better, we would like to populate the File Types dropdown on the standard Windows dialog.
    It is well known that FileNameFilter does not work on the Windows platform, so that is not a viable solution.
    We have tried JFileChooser, but performance was intolerable when a directory had many files (many = thousands). (Sure, we can tell the user not do have so many files in directories, but we can't control what the user does so this only leads to bug reports that our application is hung/broken while JFileChooser takes minutes to fill the dialog.)
    This leads me to think that we need a JNI solution for use on Windows (we can use FileNameFilter on other platforms). Are there any low cost implementations available? I'd appreciate any suggestions.
    Thank you.
    Guy

    I have used FileFilter with JFileChooser. Performance was not adequate, as I described in my post. I need a solution which a) works and b) has adequate performance.

  • Filtering in FileDialog (urgent please)

    Hello everybody,
    I was watching one problem with JFileChooser ( Error: "There is no A drive...." at this forum , as i was
    also facing the same problem. BUT when someone suggested , i tried FileDialog and I could get rid of that
    Error
    BUT now i have problem of filtering file , which was so
    easy in JFileChooser . There is getFilenameFilter() and
    setFilenameFilter(FilenameFilter ft) BUT JAVA-Api
    says that
    "...Filename filters do not function in Sun's reference implementation for Windows 95, 98, or NT 4.0."
    I didnt get it properly. Does it mean that we can filter files
    using FileDialog , if i run on these OS..?
    thanx for ur time and help..
    regds,
    Rajesh

    you can also add Windows 2000 to that.
    I am also facing the same problem. The only workaround is to use the setFile("*.ext")
    -aprajit

  • FileDialog

    How do use the FileDialog class to open a FileDialog box in your Java Program or is there something better to use?

    Please look at javax.swing.JFileChooser
    This will allow you to select (one or more ) Files or Directories while applying any filter you choose.
    -John
    null

  • FileDialog (filtering for certain file extensions)

    I have used JFileChooser in the past and was modifying my code to use FileDialog instead as it looks better, looks like the one used by every other Windows program and takes less code to get the job done. My
    question is how to filter for certain file extensions in FileDialog as you can in JFileChooser. I cannot seem to figure out how to, so any help would be highly appreciated. Thank you.
    P.S. Also if you know how to turn off all files like you can in JFileChooser, that would also be extremely helpful.

    Go to the JFileChooser tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/filechooser.html and skip to the section entitled "Filtering the List of Files". That sounds like it should answer your question.

  • JFileChooser or FileDialog??? Dilema!!

    hi there, I tried implementin a "Save As" Option using JFileChooser.. It works fine.. But wen i dont specify an extension.. it does not take the default extension specified using filters.
    Ex.. Say i try to Save "test" and the file type below reads ".xml"..It wont append the extension name.
    I can do a save as using FileDialog.. But it is not letting me filter the extensions.. I read tat filtering cannot be done on a windows platform.. but works on linux..
    So.. wha say??

    When i do a "Save As" without specifying the file
    type.. will it not take the extension from the "Save
    As" drop down box??Why would it? Appending a file extension automatically is a function of application logic that is beyond the scope of a generic component like JFileChooser. I suppose that it's possible that the equivalent file chooser component in Windows may have an option to do this for you, but that doesn't mean Java has to do the same thing.
    How...?You get the selected extension filter, if you can. You can, cuz even if JFileChooser can't tell you, you can find the combobox that it uses in the component to display that choice and get the selected value. Then you just modify the File object that you get from the chooser to a new File with the extension.
    This might be a nice function to include in a subclass of JFileChooser.

  • JFileChooser or FileDialog

    hello,
    I want to drag a file from either JFileChooser or FileDialog to a canvas what is the code for dragsource ?

    When i do a "Save As" without specifying the file
    type.. will it not take the extension from the "Save
    As" drop down box??Why would it? Appending a file extension automatically is a function of application logic that is beyond the scope of a generic component like JFileChooser. I suppose that it's possible that the equivalent file chooser component in Windows may have an option to do this for you, but that doesn't mean Java has to do the same thing.
    How...?You get the selected extension filter, if you can. You can, cuz even if JFileChooser can't tell you, you can find the combobox that it uses in the component to display that choice and get the selected value. Then you just modify the File object that you get from the chooser to a new File with the extension.
    This might be a nice function to include in a subclass of JFileChooser.

  • FileDialog Filefilter

    Hello people,
    Am having a problem using a file filter to select a particular list of files without showing all other files, but I have searched the web, but did not get an example. i don't want to use JFileChooser, I have to use the FileDialog. Please guys help a brother.
    I have encloded a sample here
    import java.awt.*;
    import java.awt.event.*;
    /** A class to test filedialogs */
    public class Filer extends Frame
    public static void main(String[] adsd){
    Filer f = new Filer();
        public Filer ()
            //setLayout (new GridLayout (5, 1));
            this.show();
           // setVisible(true);
            pack ();
            setSize(100,100);
            Button load;
            add (load = new Button ("Load..."));
            load.addActionListener (new ActionListener ()
                public void actionPerformed (ActionEvent e)
                    FileDialog d = new FileDialog (Filer.this, "Load...", FileDialog.LOAD);
                    d.pack ();
                    d.show ();
                    d.dispose ();
    }

    Thanks hiwa for your responce. I tried creating a class that implements the FilenameFilter, but it did not work. Please could you people look at my code and see where am making a mistake?
    Thanks guys.
    import java.io.*;
    import java.awt.*;
    import java.awt.event.*;                  /** A class to test filedialogs */
    public class Filer extends Frame
        public static void main (String [] adsd)
            Filer f = new Filer ();
        public Filer ()
        { //setLayout (new GridLayout (5, 1));
            this.show ();
            setVisible (true);
            pack ();
            setSize (100, 100);
            Button load;
            add (load = new Button ("Load..."));
            load.addActionListener (new ActionListener ()
                public void actionPerformed (ActionEvent e)
                    FileDialog d = new FileDialog (Filer.this, "Load...", FileDialog.LOAD);
                    d.setFilenameFilter (new ImageNameFilter ());
                    d.pack ();
                    d.show ();
                    d.dispose ();
        class ImageNameFilter implements FilenameFilter
        public boolean accept (File dir, String name)
            return (name.endsWith (".java") ||
                    name.endsWith (".JAVA"));
    }Thanks guys

  • FileDialog to restrict directory

    Hi,
    I want to allow my users to select a filename to write to, but force
    them to use a specific directory.
    I am using FileDialog and setting initial directory to the desired
    directory, but obviously they can change directory.
    Is there something other than FileDialog I can use, or a way to
    restrict the directory change ?
    Or is the only way to write my own dialog ?
    Thanks
    Sue

    Hi, thanks for reply.
    I tried the Filename filter, but couldn't get it to work.
    I added a trace to the accept method and that didn't come out, so I'm
    a bit confused.
    Does my code look ok ?
    public class MyFilenameFilter implements FilenameFilter {
    public MyFilenameFilter() {
    public boolean accept(File dir, String name) {
    System.out.println("Accept " + dir.getAbsolutePath() + " " + name);
    if (dir.getAbsolutePath().compareToIgnoreCase("c:/myDir") != 0)
    return false;
    else
    return true;
    Then to use it I have :-
    FileDialog fd = new FileDialog((Frame)parent, "Test", FileDialog.SAVE);
    fd.setFilenameFilter(new MyFilenameFilter());
    fd.show();
    Thanks
    Sue

Maybe you are looking for