Skip to content

Instantly share code, notes, and snippets.

@YounesCheikh
Created November 25, 2012 19:39
Show Gist options
  • Save YounesCheikh/4144967 to your computer and use it in GitHub Desktop.
Save YounesCheikh/4144967 to your computer and use it in GitHub Desktop.
Tutorial explains how to use JFileChosser Properly [Part 1]
/*
* Tutorial: How to use JFileChooser properly (1)
* URL: http://cyounes.com/tutorials/how-to-use-jfilechooser-properly
* @author Cheikh Younes
*/
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JTextField;
public class MyWindow extends JFrame {
private JButton btn ;
private JTextField textField;
private JFileChooser fc;
public MyWindow() {
initComponents();
simpleMethod();
}
private void initComponents() {
setSize(300, 60);
setTitle("My Window");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container c = getContentPane();
c.setLayout(new FlowLayout());
btn = new JButton("Browse");
btn.setPreferredSize(new Dimension(100, 20));
c.add(btn);
textField = new JTextField();
textField.setPreferredSize(new Dimension(160, 20));
c.add(textField);
}
private void simpleMethod() {
btn.addActionListener(new java.awt.event.ActionListener() {
@Override
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnBrowseActionPerformed(evt);
}
});
}
private void btnBrowseActionPerformed(java.awt.event.ActionEvent evt) {
if (fc == null) {
fc = new JFileChooser(".");
}
// Show it.
int returnVal = fc.showOpenDialog(this);
// Process the results.
if (returnVal == JFileChooser.APPROVE_OPTION) {
textField.setText(fc.getSelectedFile().getPath());
} else {
textField.setText("");
}
// Reset the file chooser for the next time it's shown.
fc.setSelectedFile(null);
}
public static void main(String[] args) {
MyWindow window = new MyWindow();
window.setVisible(true);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment