Java Development Notes (135) Swing's File Dialog

Keywords: Java

In addition to the regular prompt dialogs, there is also a dialog box that is also common, called a file dialog box.File dialogs are divided into two subcategories: the dialog to open a file and the dialog to save a file, but in Swing they are all represented by the type JFileChooser.Following is a description of the common methods used by JFileChooser:
setDialogTitle: Sets the title of the file dialog box.
setApproveButtonText: Sets the text of the OK button.
setCurrentDirectory: Sets the initial directory of the file dialog box.
setMultiSelectionEnabled: Sets whether multiple file selection is supported.A value of true supports multiple selection, false does not support multiple selection, and multiple selection is not allowed by default.
setFileSelectionMode: Sets the file selection mode.There are three modes of selection: JFileChooser.FILES_ONLY (only showing files, but also directories for actual test findings), JFileChooser.DIRECTORIES_ONLY (only showing directories), JFileChooser.FILES_AND_DIRECTORIES (showing files and directories).
setFileFilter: Sets the filter for file selection.
setDialogType: Sets the type of dialog.Value JFileChooser.OPEN_DIALOG means this is the file open dialog box, and JFileChooser.SAVE_DIALOGG means this is the file save dialog box.
showOpenDialog: Displays the file open dialog.The return value of this method indicates whether the file is selected or not. For JFileChooser.APPROVE_OPTION, the OK button is pressed on the dialog box, and for JFileChooser.CANCEL_OPTION, the Cancel button is pressed on the dialog box.
showSaveDialog: Displays the file save dialog.The return value of this method indicates the same as showOpenDialog.
getSelectedFile: Gets the currently selected file object.
getSelectedFiles: Gets the currently selected array of file objects only if there are multiple selections.
Of the above methods, it is particularly important to note that setFileFilter, which at first appears to have a FileFilter input parameter, is not a file filter under java.io, but Swing's own file dialog filter.This filter has the same accept method as the IO library's filter with the same name to determine if the current file meets the filter criteria; the difference is that there are more getDescription methods in the filter of the file dialog box, and the return string of the method is displayed in the file type drop-down list inside the dialog box, which is equivalent to givingMake a supplementary note about the file type.For example, txt type is commonly called text file, jpg, gif, png are several types of picture file, ppt, pptx type is called slide file, and so on.The specific file filter call code example is as follows:

		JFileChooser chooser = new JFileChooser(); // Create a file dialog
		chooser.setCurrentDirectory(new File("E:/")); // Set Current Directory of File Dialog
		chooser.setFileFilter(new FileFilter() { // Set File Filter for File Dialog
			@Override
			public boolean accept(File file) { // Determines if the current file meets the filter criteria, and only if it meets the criteria will it appear in the dialog box
				// The directory meets the criteria, and the file with the extension txt meets the criteria
				return file.isDirectory() || file.getName().toLowerCase().endsWith(".txt");
			}

			@Override
			public String getDescription() { // Get a description of the filter
				return "*.txt(text file)";
			}
		});

Next, to demonstrate how to manipulate the file dialog box, register the Click Listener for a button and call the showOpenDialog method to pop up the file dialog box when the button is clicked.With the file open dialog as an example, the specific calling code is as follows:

		btnOpenFile.addActionListener(new ActionListener() { // Register a click listener for the button
			@Override
			public void actionPerformed(ActionEvent e) { // A click event occurred
				// Set the type of file dialog, where the dialog is ready to open the file
				chooser.setDialogType(JFileChooser.OPEN_DIALOG);
				// Show file open dialog
				int result = chooser.showOpenDialog(frame);
				if (result == JFileChooser.APPROVE_OPTION) { // Clicked the OK button
					// Gets the file selected in the file dialog
					File file = chooser.getSelectedFile();
					label.setText("<html>The file path to open is:" + file.getAbsolutePath() + "</html>");
				} else { // No OK button clicked
					label.setText("Cancel opening file");
				}
			}
		});

 

Run the test program and click the file pop-up button to open the dialog box as shown in the following figure.


Double-click the subdirectory inside the file dialog box to find a text file and click it. The File Name column of the file dialog box shows the name of the file, indicating that the file has been selected. The dialog interface is shown in the following figure.

Then click the Open button under the dialog box to go back to the main interface of the program as shown in the figure below. You can see that the main interface successfully knows the full path of the file you just selected.



Register the Click Listener for another button as well, call the showSaveDialog method when clicking the button to bring up the File Save dialog box, where the calling code is as follows:

		btnSaveFile.addActionListener(new ActionListener() { // Register a click listener for the button
			@Override
			public void actionPerformed(ActionEvent e) { // A click event occurred
				// Set the type of file dialog, where the dialog is ready to save the file
				chooser.setDialogType(JFileChooser.SAVE_DIALOG);
				// Show file save dialog
				int result = chooser.showSaveDialog(frame);
				if (result == JFileChooser.APPROVE_OPTION) { // Clicked the OK button
					// Gets the file selected in the file dialog
					File file = chooser.getSelectedFile();
					label.setText("<html>The file path to save is:" + file.getAbsolutePath() + "</html>");
				} else { // No OK button clicked
					label.setText("Cancel Save File");
				}
			}
		});

 

Run the test program and click the button to display the file save dialog as shown in the following figure.


Compared with the File Open dialog box, the top left title of the File Save dialog box is changed from Open to Save and the bottom Open button is changed to Save. Except for these two changes, everything else is the same.In the File Name column of the dialog box, fill in the name of the file to be saved, and then click the Save button to go back to the program main interface as shown in the figure below. You can see that the main interface successfully knows the full path of the file to be saved.


The internal font of a file dialog cannot be modified directly by the setFont method either, because the dialog box is just a frame, and there are many controls inside the frame, so it is necessary to traverse these internal controls and set the text font of each control one by one.The detailed dialog font setting method is defined as follows:

	// Set the internal font of the dialog box.The first parameter requires an instance of the incoming file dialog
	private static void setComponentFont(Component component, Font font) {
		component.setFont(font); // Set the font of the current component
		if (component instanceof Container) { // If the component is a container
			Container container = (Container) component; // Force this component into a container
			int count = container.getComponentCount(); // Gets the number of components inside the container
			for (int i = 0; i < count; i++) { // Traverse all components of the container
				// Set the internal font again for each component
				setComponentFont(container.getComponent(i), font);
			}
		}
	}

 



For more Java technical articles see " Java Development Notes (Sequence) Chapter Program Directory>

Posted by rempires on Fri, 09 Aug 2019 20:41:06 -0700