JFileChooser es parte del paquete Java Swing. El paquete java Swing es parte de JavaTM Foundation Classes (JFC) . JFC contiene muchas funciones que ayudan a crear una interfaz gráfica de usuario en Java. Java Swing proporciona componentes como botones, paneles, cuadros de diálogo, etc. JFileChooser es una forma fácil y efectiva de solicitar al usuario que elija un archivo o un directorio.
En este artículo veremos cómo usar JFileChooser en java swing.
Los constructores de JFileChooser son:
1. JFileChooser() : constructor vacío que apunta al directorio predeterminado del usuario
Java
// Using this process to invoke the constructor, // JFileChooser points to user's default directory JFileChooser j = new JFileChooser(); // Open the save dialog j.showSaveDialog(null);
Salida del fragmento de código:
2. JFileChooser(String) – usa la ruta dada
Java
// Using this process to invoke the constructor, // JFileChooser points to the mentioned path JFileChooser j = new JFileChooser("d:"); // Open the save dialog j.showSaveDialog(null);
Salida del fragmento de código:
3. JFileChooser(File) – utiliza el archivo dado como ruta
Java
// Using this process to invoke the constructor, // JFileChooser points to the mentioned path // of the file passed JFileChooser j = new JFileChooser(new File("C:\\Users\\pc\\Documents\\New folder\\")); // Open the save dialog j.showSaveDialog(null);
Salida del fragmento de código:
4. JFileChooser(FileSystemView) – usa el FileSystemView dado
Java
// In this process argument passed // is an object of File System View JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView()); // Open the save dialog j.showSaveDialog(null);
Salida del fragmento de código:
5. JFileChooser(String, FileSystemView) – usa la ruta dada y el FileSystemView
Java
// In this process argument passed is an object // of File System View, and a path JFileChooser j = new JFileChooser("d:", FileSystemView.getFileSystemView()); // Open the save dialog j.showSaveDialog(null);
Salida del fragmento de código:
6. JFileChooser(File, FileSystemView) – usa el directorio actual dado y el FileSystemView
Java
// In this process argument passed is an object // of File System View and a object of // File class File f = new File("C:\\Users\\pc\\Documents\\New folder\\"); JFileChooser j = new JFileChooser(f, FileSystemView.getFileSystemView()); // Open the save dialog j.showSaveDialog(null);
Salida del fragmento de código:
Nota: el código proporcionado anteriormente son fragmentos de código, no el código completo, los fragmentos de código proporcionados anteriormente deben usarse para invocar al constructor según la necesidad y la discreción del programador, las rutas mencionadas anteriormente son arbitrarias. El usuario debe establecer la ruta de acuerdo a sus necesidades.
Aplicaciones prácticas de JFileChooser
Los siguientes códigos no se ejecutarán en un compilador en línea. Utilice un IDE sin conexión
1. Creación de un cuadro de diálogo para abrir o guardar con JFileChooser
Java
// Java program to create open or // save dialog using JFileChooser import java.io.*; import javax.swing.*; import java.awt.event.*; import javax.swing.filechooser.*; class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame("file chooser"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton("save"); // button to open open dialog JButton button2 = new JButton("open"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel("no file selected"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals("save")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } } }
2. Use JFileChooser para seleccionar solo el directorio
Java
// Java program to use JFileChooser // to select directory only import java.io.*; import javax.swing.*; import java.awt.event.*; import javax.swing.filechooser.*; class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame("file chooser to select directories"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton("save"); // button to open open dialog JButton button2 = new JButton("open"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel("no file selected"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals("save")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // set the selection mode to directories only j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected directory l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // set the selection mode to directories only j.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected directory l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } } }
3. Use JFileChooser para permitir la selección múltiple de archivos
Java
// Java program to use JFileChooser to allow multiple selection of files import java.io.*; import javax.swing.*; import java.awt.event.*; import javax.swing.filechooser.*; class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame("file chooser to select multiple files at a time"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton("save"); // button to open open dialog JButton button2 = new JButton("open"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel("no file selected"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals("save")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // allow multiple file selection j.setMultiSelectionEnabled(true); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // get the Selected files File files[] = j.getSelectedFiles(); int t = 0; // set text to blank l.setText(""); // set the label to the path of the selected files while (t++ < files.length) l.setText(l.getText() + " " + files[t - 1].getName()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // allow multiple file selection j.setMultiSelectionEnabled(true); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); if (r == JFileChooser.APPROVE_OPTION) { // get the Selected files File files[] = j.getSelectedFiles(); // set text to blank l.setText(""); int t = 0; // set the label to the path of the selected files while (t++ < files.length) l.setText(l.getText() + " " + files[t - 1].getName()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } } }
4. Use JFileChooser para restringir el tipo de archivos que se muestran al usuario
Java
// Java program to use JFileChooser to restrict // the type of files shown to the user import java.io.*; import javax.swing.*; import java.awt.event.*; import javax.swing.filechooser.*; class filechooser extends JFrame implements ActionListener { // Jlabel to show the files user selects static JLabel l; // a default constructor filechooser() { } public static void main(String args[]) { // frame to contains GUI elements JFrame f = new JFrame("file chooser"); // set the size of the frame f.setSize(400, 400); // set the frame's visibility f.setVisible(true); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // button to open save dialog JButton button1 = new JButton("save"); // button to open open dialog JButton button2 = new JButton("open"); // make an object of the class filechooser filechooser f1 = new filechooser(); // add action listener to the button to capture user // response on buttons button1.addActionListener(f1); button2.addActionListener(f1); // make a panel to add the buttons and labels JPanel p = new JPanel(); // add buttons to the frame p.add(button1); p.add(button2); // set the label to its initial value l = new JLabel("no file selected"); // add panel to the frame p.add(l); f.add(p); f.show(); } public void actionPerformed(ActionEvent evt) { // if the user presses the save button show the save dialog String com = evt.getActionCommand(); if (com.equals("save")) { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // restrict the user to select files of all types j.setAcceptAllFileFilterUsed(false); // set a title for the dialog j.setDialogTitle("Select a .txt file"); // only allow files of .txt extension FileNameExtensionFilter restrict = new FileNameExtensionFilter("Only .txt files", "txt"); j.addChoosableFileFilter(restrict); // invoke the showsSaveDialog function to show the save dialog int r = j.showSaveDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } // if the user presses the open dialog show the open dialog else { // create an object of JFileChooser class JFileChooser j = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); // restrict the user to select files of all types j.setAcceptAllFileFilterUsed(false); // set a title for the dialog j.setDialogTitle("Select a .txt file"); // only allow files of .txt extension FileNameExtensionFilter restrict = new FileNameExtensionFilter("Only .txt files", "txt"); j.addChoosableFileFilter(restrict); // invoke the showsOpenDialog function to show the save dialog int r = j.showOpenDialog(null); // if the user selects a file if (r == JFileChooser.APPROVE_OPTION) { // set the label to the path of the selected file l.setText(j.getSelectedFile().getAbsolutePath()); } // if the user cancelled the operation else l.setText("the user cancelled the operation"); } } }
NOTA:
también puede personalizar el botón de aprobación mediante la función setApproveButtonText(String) . Esto establecerá el texto del botón aprobado
en el texto deseado.
Publicación traducida automáticamente
Artículo escrito por andrew1234 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA