• Post Reply Bookmark Topic Watch Topic
  • New Topic

filters with filechooser

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dear sir/madam,

can anyone give small code for using filters within
JFilechooser and opening a new file
regards
srijan
 
deekasha gunwant
Ranch Hand
Posts: 396
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello srijan,
i've tried to write the code.may be it'll help u. just copy compile and run the code. it will open up a frame with a button on it. click it and u'll see a filechooser which will show u only directories &.java files. the code goes like this -----------
=====================================================
CODE STARTS HERE
=====================================================
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.filechooser.*;
import java.io.File;

public class Fr extends JFrame
{
JButton jb = new JButton("File Chooser");
JTextField nameField = new JTextField("i'm a text field");
public Fr()
{
this.getContentPane().setLayout(new FlowLayout());
this.getContentPane().add(jb);
this.getContentPane().add(nameField);

//clicking the button will open the filechooser
jb.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae)
{
JFileChooser jfchr = new JFileChooser();
// an instance of Myfilter is associated with filechooser
jfchr.setFileFilter( new MyFilter());
// a file open dialog should open up
int ret = jfchr.showOpenDialog(Fr.this);
// text field shows whether user pressed cancel button or open button
if(ret == JFileChooser.CANCEL_OPTION)
nameField.setText("cancelled");
else if(ret == JFileChooser.APPROVE_OPTION)
nameField.setText("Approved");
}
});
}

public static void main(String h[])
{
Fr f = new Fr();
f.setSize(200,200);
f.setVisible(true);
}

}
//// FileFilter class is extended to make a filter
//// that will show only .java files and directories
class MyFilter extends FileFilter
{
/// accept function is implemented to do the required filtering
public boolean accept(File f)
{

if(!f.isFile())
return true;
String s = f.getName();
if(s.endsWith(".java"))
return true;
else
return false;
}


//// this function is used coz it is defined abstract in filefilter
//// class so we have to give its body.
public String getDescription()
{
return "MyFilter";
}
}


========================================================
END OF CODE
=======================================================
let me know if it was okay
regards
deekasha
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!