Java диалог выбора файла
JFileChooser provides a simple mechanism for the user to choose a file. For information about using JFileChooser , see How to Use File Choosers, a section in The Java Tutorial.
The following code pops up a file chooser for the user's home directory that sees only .jpg and .jpg images:
Warning: Swing is not thread safe. For more information see Swing's Threading Policy.
Method Details
Диалоговые окна подтверждений ConfirmDialog
Листинг процедуры создания слушателей, формирующие диалоговые окна подтверждений.
В зависимости от нажатой кнопки открываются следующее окно подтверждение (одно из окон на следующем скриншот), конструктор которого получает 2 параметра. Текст заголовка имеет значение по умолчанию «Select an Option».
Nested classes/interfaces inherited from class javax.swing.JComponent
MULTI_SELECTION_ENABLED_CHANGED_PROPERTY
Field Summary
Modifier and Type | Field and Description |
---|---|
static String | ACCEPT_ALL_FILE_FILTER_USED_CHANGED_PROPERTY |
Identifies a change in the type of files displayed (files only, directories only, or both files and directories).
Field Details
Nested classes/interfaces inherited from class java.awt.Container
APPROVE_SELECTION
getFileSelectionMode
- JFileChooser.FILES_ONLY
- JFileChooser.DIRECTORIES_ONLY
- JFileChooser.FILES_AND_DIRECTORIES
getChoosableFileFilters
CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY
changeToParentDirectory
CANCEL_SELECTION
Диалоговое окно FontDialog
Экземпляр класса FontDialog позволяет пользователю выбрать шрифт из всех возможных шрифтов, установленных в системе.
Конструкторы FontDialog
Конструктор создания диалогового окна выбора шрифта FontDialog в качестве параметра принимает родительское окно parent.
Основные методы FontDialog
Метод | Описание |
---|---|
FontData[] getFontList() | Функция получения списка описания шрифтов |
RGB getRGB() | Функция получения цвета шрифта |
FontData open() | Функция открытия FontDialog и размещение его над остальными окнами |
void setFontList(FontData[] fontData) | Метод определения выделенных шрифтов в диалоговом окне FontDialog |
void setRGB(RGB rgb) | Метод определения цвета шрифта по умолчанию. |
Экземпляр класса FontData описывает шрифт операционной системы, включающего следующие поля :
- height - высота шрифта в пискелях;
- name - наименование шрифта;
- style - стиль шрифта (сочетание [NORMAL, ITALIC] и BOLD).
Конструкторы FontData
Основные методы FontData
Метод | Описание |
---|---|
int getHeight() | Функция чтения размера шрифта в пискелях |
String getLocale() | Функция чтения Locale |
String getName() | Функция чтения наименования шрифта |
int getStyle() | Функция чтения стиля шрифта |
void setHeight(int height) | Функция определения размера шрифта в пискелях |
void setLocale(String locale) | Функция определения Locale |
void setName(String name) | Функция определения наименования шрифта |
void setStyle(int style) | Функция определения стиля шрифта |
Пример открытия диалог FontDialog
В следующем примере формируется диалоговое окно FontDialog для определения шрифта.
Интерфейс диалогового окна определения шрифта FontDialog представлен на следующем скриншоте.
Конструкторы MessageBox
Стили MessageBox
- изображение в окне - ICON_ERROR, ICON_INFORMATION, ICON_QUESTION, ICON_WARNING, ICON_WORKING
- кнопки - OK, OK | CANCEL
- кнопки - YES | NO, YES | NO | CANCEL
- кнопки - RETRY | CANCEL
- кнопки - ABORT | RETRY | IGNORE
Основные методы MessageBox
JOptionPane унаследован от базового класса JComponent библиотеки Swing, так что можно работать с ним напрямую, т.е. создавать экземпляры класса JOptionPane и настраивать их свойства. Использование стандартных диалоговых окон существенно упрощает разработку приложения и позволяет ускорить процесс освоения пользователем интерфейса.
Все стандартные диалоговые окна Swing имеют собственные UI-представители, отвечающие за интерфейс окна в используемом приложении. Это особенно важно для внешних видов окон, имитирующих известные платформы, пользователи которых не должны ощущать значительной разницы при переходе от «родных» приложений к Java-приложениям.
setCurrentDirectory
@BeanProperty(preferred=true, description="The directory that the JFileChooser is showing files of.") public void setCurrentDirectory ( File dir)
Sets the current directory. Passing in null sets the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix. If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.
getCurrentDirectory
Method Detail
setup
setDragEnabled
Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component. The transferHandler property needs to be set to a non- null value for the drag to do anything. The default value of the dragEnabled property is false .
When automatic drag handling is enabled, most look and feels begin a drag-and-drop operation whenever the user presses the mouse button over an item and then moves the mouse a few pixels. Setting this property to true can therefore have a subtle effect on how selections behave.
Some look and feels might not support automatic drag and drop; they will ignore this property. You can work around such look and feels by modifying the component to directly call the exportAsDrag method of a TransferHandler .
getDragEnabled
getSelectedFile
Returns the selected file. This can be set either by the programmer via setSelectedFile or by a user action, such as either typing the filename into the UI or selecting the file from a list in the UI.
setSelectedFile
Sets the selected file. If the file's parent directory is not the current directory, changes the current directory to be the file's parent directory.
getSelectedFiles
setSelectedFiles
getCurrentDirectory
setCurrentDirectory
Sets the current directory. Passing in null sets the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix. If the file passed in as currentDirectory is not a directory, the parent of the file will be used as the currentDirectory. If the parent is not traversable, then it will walk up the parent tree until it finds a traversable directory, or hits the root of the file system.
changeToParentDirectory
rescanCurrentDirectory
ensureFileIsVisible
showOpenDialog
Pops up an "Open File" file chooser dialog. Note that the text that appears in the approve button is determined by the L&F.
- JFileChooser.CANCEL_OPTION
- JFileChooser.APPROVE_OPTION
- JFileChooser.ERROR_OPTION if an error occurs or the dialog is dismissed
showSaveDialog
Pops up a "Save File" file chooser dialog. Note that the text that appears in the approve button is determined by the L&F.
- JFileChooser.CANCEL_OPTION
- JFileChooser.APPROVE_OPTION
- JFileChooser.ERROR_OPTION if an error occurs or the dialog is dismissed
showDialog
Pops a custom file chooser dialog with a custom approve button. For example, the following code pops up a file chooser with a "Run Application" button (instead of the normal "Save" or "Open" button): Alternatively, the following code does the same thing:
The parent argument determines two things: the frame on which the open dialog depends and the component whose position the look and feel should consider when placing the dialog. If the parent is a Frame object (such as a JFrame ) then the dialog depends on the frame and the look and feel positions the dialog relative to the frame (for example, centered over the frame). If the parent is a component, then the dialog depends on the frame containing the component, and is positioned relative to the component (for example, centered over the component). If the parent is null , then the dialog depends on no visible window, and it's placed in a look-and-feel-dependent position such as the center of the screen.
- JFileChooser.CANCEL_OPTION
- JFileChooser.APPROVE_OPTION
- JFileChooser.ERROR_OPTION if an error occurs or the dialog is dismissed
createDialog
Creates and returns a new JDialog wrapping this centered on the parent in the parent 's frame. This method can be overriden to further manipulate the dialog, to disable resizing, set the location, etc. Example:
getControlButtonsAreShown
setControlButtonsAreShown
Sets the property that indicates whether the approve and cancel buttons are shown in the file chooser. This property is true by default. Look and feels that always show these buttons will ignore the value of this property. This method fires a property-changed event, using the string value of CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY as the name of the property.
getDialogType
- JFileChooser.OPEN_DIALOG
- JFileChooser.SAVE_DIALOG
- JFileChooser.CUSTOM_DIALOG
setDialogType
Sets the type of this dialog. Use OPEN_DIALOG when you want to bring up a file chooser that the user can use to open a file. Likewise, use SAVE_DIALOG for letting the user choose a file for saving. Use CUSTOM_DIALOG when you want to use the file chooser in a context other than "Open" or "Save". For instance, you might want to bring up a file chooser that allows the user to choose a file to execute. Note that you normally would not need to set the JFileChooser to use CUSTOM_DIALOG since a call to setApproveButtonText does this for you. The default dialog type is JFileChooser.OPEN_DIALOG .
- JFileChooser.OPEN_DIALOG
- JFileChooser.SAVE_DIALOG
- JFileChooser.CUSTOM_DIALOG
setDialogTitle
getDialogTitle
setApproveButtonToolTipText
Sets the tooltip text used in the ApproveButton . If null , the UI object will determine the button's text.
getApproveButtonToolTipText
Returns the tooltip text used in the ApproveButton . If null , the UI object will determine the button's text.
getApproveButtonMnemonic
setApproveButtonMnemonic
setApproveButtonMnemonic
setApproveButtonText
getApproveButtonText
Returns the text used in the ApproveButton in the FileChooserUI . If null , the UI object will determine the button's text. Typically, this would be "Open" or "Save".
getChoosableFileFilters
addChoosableFileFilter
Adds a filter to the list of user choosable file filters. For information on setting the file selection mode, see setFileSelectionMode .
removeChoosableFileFilter
Removes a filter from the list of user choosable file filters. Returns true if the file filter was removed.
resetChoosableFileFilters
Resets the choosable file filter list to its starting state. Normally, this removes all added file filters while leaving the AcceptAll file filter.
getAcceptAllFileFilter
isAcceptAllFileFilterUsed
setAcceptAllFileFilterUsed
Determines whether the AcceptAll FileFilter is used as an available choice in the choosable filter list. If false, the AcceptAll file filter is removed from the list of available file filters. If true, the AcceptAll file filter will become the the actively used file filter.
getAccessory
setAccessory
Sets the accessory component. An accessory is often used to show a preview image of the selected file; however, it can be used for anything that the programmer wishes, such as extra custom file chooser controls.
Note: if there was a previous accessory, you should unregister any listeners that the accessory might have registered with the file chooser.
setFileSelectionMode
Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories. The default is JFilesChooser.FILES_ONLY .
- JFileChooser.FILES_ONLY
- JFileChooser.DIRECTORIES_ONLY
- JFileChooser.FILES_AND_DIRECTORIES
getFileSelectionMode
- JFileChooser.FILES_ONLY
- JFileChooser.DIRECTORIES_ONLY
- JFileChooser.FILES_AND_DIRECTORIES
isFileSelectionEnabled
isDirectorySelectionEnabled
Convenience call that determines if directories are selectable based on the current file selection mode.
setMultiSelectionEnabled
isMultiSelectionEnabled
isFileHidingEnabled
setFileHidingEnabled
Sets file hiding on or off. If true, hidden files are not shown in the file chooser. The job of determining which files are shown is done by the FileView .
setFileFilter
Sets the current file filter. The file filter is used by the file chooser to filter out files from the user's view.
getFileFilter
setFileView
Sets the file view to used to retrieve UI information, such as the icon that represents a file or the type description of a file.
setApproveButtonToolTipText
@BeanProperty(preferred=true, description="The tooltip text for the ApproveButton.") public void setApproveButtonToolTipText ( String toolTipText)
Sets the tooltip text used in the ApproveButton . If null , the UI object will determine the button's text.
DIRECTORY_CHANGED_PROPERTY
APPROVE_BUTTON_TOOL_TIP_TEXT_CHANGED_PROPERTY
getFileFilter
setDialogTitle
@BeanProperty(preferred=true, description="The title of the JFileChooser dialog window.") public void setDialogTitle ( String dialogTitle)
getAcceptAllFileFilter
getControlButtonsAreShown
DIALOG_TYPE_CHANGED_PROPERTY
Identifies a change in the type of files displayed (files only, directories only, or both files and directories).
getAccessory
Диалоговое окно PrintDialog
Конструкторы PrintDialog
Основные методы PrintDialog
Метод | Описание |
---|---|
int getEndPage() | Функция получения последней выбранной пользователем страницы перед отправлением задания на печать |
PrinterData open() | Функция открытия диалогового окна PrintDialog и размещение его над всеми остальными окнами |
PrinterData getPrinterData() | Получение данных печати при открытии диалогового окна PrintDialog |
boolean getPrintToFile() | Функция получения 'Print to file' настройки, выбранные пользователем |
int getScope() | Функция определения цели печати |
int getStartPage() | Функция получения начальной страницы печати |
void setEndPage(int endPage) | Метод определения последней страницы печати |
void setPrinterData(PrinterData data) | Метод определения параметров печати перед открытием окна PrintDialog |
void setPrintToFile(boolean printToFile) | Метод определения настройки 'Print to file' |
void setScope(int scope) | Метод определения цели печати |
void setStartPage(int startPage) | Метод определения первой страницы печати, которую пользователь увидит в PrintDialog. |
Класс PrinterData наследует DeviceData, описывает задание на печать в терминах printer'a и имеет следующие поля :
- static int ALL_PAGES
- boolean collate
- int copyCount
- String driver
- int duplex
- static int DUPLEX_LONG_EDGE
- static int DUPLEX_NONE
- static int DUPLEX_SHORT_EDGE
- int endPage
- String fileName
- static int LANDSCAPE
- String name
- int orientation
- static int PAGE_RANGE
- static int PORTRAIT
- boolean printToFile
- int scope
- static int SELECTION
- int startPage
Пример открытия диалогового окна PrintDialog
В следующем примере формируется диалоговое окно печати.
Интерфейс диалогового окна печати PrintDialog представлен на следующем скриншоте.
getDragEnabled
FILE_FILTER_CHANGED_PROPERTY
CANCEL_OPTION
setDialogType
Sets the type of this dialog. Use OPEN_DIALOG when you want to bring up a file chooser that the user can use to open a file. Likewise, use SAVE_DIALOG for letting the user choose a file for saving. Use CUSTOM_DIALOG when you want to use the file chooser in a context other than "Open" or "Save". For instance, you might want to bring up a file chooser that allows the user to choose a file to execute. Note that you normally would not need to set the JFileChooser to use CUSTOM_DIALOG since a call to setApproveButtonText does this for you. The default dialog type is JFileChooser.OPEN_DIALOG .
- JFileChooser.OPEN_DIALOG
- JFileChooser.SAVE_DIALOG
- JFileChooser.CUSTOM_DIALOG
isMultiSelectionEnabled
setSelectedFiles
@BeanProperty(description="The list of selected files if the chooser is in multiple selection mode.") public void setSelectedFiles ( File[] selectedFiles)
APPROVE_OPTION
Methods declared in class java.awt.Container
rescanCurrentDirectory
JFileChooser
Constructs a JFileChooser using the given File as the path. Passing in a null file causes the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix.
SELECTED_FILE_CHANGED_PROPERTY
Method Summary
Convenience call that determines if directories are selectable based on the current file selection mode.
Determines whether the AcceptAll FileFilter is used as an available choice in the choosable filter list.
Sets the property that indicates whether the approve and cancel buttons are shown in the file chooser.
Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component.
Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories.
Sets the file system view that the JFileChooser uses for accessing and creating file system resources, such as finding the floppy drive and getting a list of root drives.
Sets the file view to be used to retrieve UI information, such as the icon that represents a file or the type description of a file.
createDialog
Creates and returns a new JDialog wrapping this centered on the parent in the parent 's frame. This method can be overriden to further manipulate the dialog, to disable resizing, set the location, etc. Example:
setAccessory
@BeanProperty(preferred=true, description="Sets the accessory component on the JFileChooser.") public void setAccessory ( JComponent newAccessory)
Sets the accessory component. An accessory is often used to show a preview image of the selected file; however, it can be used for anything that the programmer wishes, such as extra custom file chooser controls.
Note: if there was a previous accessory, you should unregister any listeners that the accessory might have registered with the file chooser.
setFileHidingEnabled
@BeanProperty(preferred=true, description="Sets file hiding on or off.") public void setFileHidingEnabled ( boolean b)
Sets file hiding on or off. If true, hidden files are not shown in the file chooser. The job of determining which files are shown is done by the FileView .
JFileChooser
Constructs a JFileChooser using the given path. Passing in a null string causes the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix.
APPROVE_BUTTON_TEXT_CHANGED_PROPERTY
FILE_SELECTION_MODE_CHANGED_PROPERTY
Constructor Summary
Methods declared in class javax.swing.JComponent
FILE_HIDING_CHANGED_PROPERTY
showDialog
Pops a custom file chooser dialog with a custom approve button. For example, the following code pops up a file chooser with a "Run Application" button (instead of the normal "Save" or "Open" button): Alternatively, the following code does the same thing:
The parent argument determines two things: the frame on which the open dialog depends and the component whose position the look and feel should consider when placing the dialog. If the parent is a Frame object (such as a JFrame ) then the dialog depends on the frame and the look and feel positions the dialog relative to the frame (for example, centered over the frame). If the parent is a component, then the dialog depends on the frame containing the component, and is positioned relative to the component (for example, centered over the component). If the parent is null , then the dialog depends on no visible window, and it's placed in a look-and-feel-dependent position such as the center of the screen.
- JFileChooser.CANCEL_OPTION
- JFileChooser.APPROVE_OPTION
- JFileChooser.ERROR_OPTION if an error occurs or the dialog is dismissed
JFileChooser
Пример использования JOptionPane
Пример JOptionPaneTest.java включает использование всех типов диалоговых окон JOptionPane. В интерфейсе окна, представленном на следующем скриншоте, размещаются кнопки, по нажатию на которые формируются соответствующие диалоговые окна JOptionPane.
Листинг примера JOptionPane
В методах addMessageListeners(), addConfirmListeners(), addInputListeners() определяются слушатели, обрабатывающие нажатие соответствующих кнопок.
setup
FILE_VIEW_CHANGED_PROPERTY
Methods inherited from class java.lang.Object
CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY
Constructor Summary
isFileHidingEnabled
FILE_SYSTEM_VIEW_CHANGED_PROPERTY
isFileSelectionEnabled
Field Detail
OPEN_DIALOG
SAVE_DIALOG
CUSTOM_DIALOG
CANCEL_OPTION
APPROVE_OPTION
ERROR_OPTION
FILES_ONLY
DIRECTORIES_ONLY
FILES_AND_DIRECTORIES
CANCEL_SELECTION
APPROVE_SELECTION
APPROVE_BUTTON_TEXT_CHANGED_PROPERTY
APPROVE_BUTTON_TOOL_TIP_TEXT_CHANGED_PROPERTY
APPROVE_BUTTON_MNEMONIC_CHANGED_PROPERTY
CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY
DIRECTORY_CHANGED_PROPERTY
SELECTED_FILE_CHANGED_PROPERTY
SELECTED_FILES_CHANGED_PROPERTY
MULTI_SELECTION_ENABLED_CHANGED_PROPERTY
FILE_SYSTEM_VIEW_CHANGED_PROPERTY
FILE_VIEW_CHANGED_PROPERTY
FILE_HIDING_CHANGED_PROPERTY
FILE_FILTER_CHANGED_PROPERTY
FILE_SELECTION_MODE_CHANGED_PROPERTY
ACCESSORY_CHANGED_PROPERTY
ACCEPT_ALL_FILE_FILTER_USED_CHANGED_PROPERTY
DIALOG_TITLE_CHANGED_PROPERTY
DIALOG_TYPE_CHANGED_PROPERTY
Identifies a change in the type of files displayed (files only, directories only, or both files and directories).
CHOOSABLE_FILE_FILTER_CHANGED_PROPERTY
accessibleContext
JFileChooser
getDialogTitle
Диалоговое окно FileDialog
Конструкторы FileDialog
Конструктор создания диалогового окна работы с файлами FileDialog в качестве параметра принимает родительское окно parent. Второму конструктору дополнительно необходимо передать стиль style, который может принимать одно из значений [SWT.SAVE, SWT.OPEN, SWT.MULTI] и определяет интерфейс и поведение диалогового окна FileDialog.
Основные методы FileDialog
Метод | Описание |
---|---|
String getFileName() | Функция получения выбранного файла относительно пути фильтра. Если файл не выбран, то функция вернет пустую строку |
String[] getFileNames() | Функция получения массива файлов относительно пути фильтра. Если файлы не выбраны, то функция вернет пустой массив |
String[] getFilterExtensions() | Функция получения расширений файлов, которые FileDialog будет использовать для фильтрации |
int getFilterIndex() | Функция получения индекса массива описаний фильтра, который был выбран пользователем. Отсчет от 0. Функция вернет -1, если фильтр не был использован |
String getFilterPath() | Функция получения пути фильтра директории, который использовал FileDialog. Если фильтр не был использован, то функция вернет пустую строку |
String open() | Функция открытия диалогового окна FileDialog и размещение его над всеми остальными окнами |
void setFileName(String string) | Определение наименования файла (может быть null), который FileDialog выделит при открытии окна |
void setFilterExtensions(String[] extensions) | Определение расширений файлов (может быть null), которые FileDialog будет использовать для фильтрации файлов |
void setFilterIndex(int index) | Определение расширения файлов согласно индексу массива фильтров, который FileDialog будет использовать при инициализации окна |
void setFilterNames(String[] names) | Определение наименований фильтров согласно списку расширений, которые использует FileDialog |
void setFilterPath(String string) | Определение пути директории (может быть null), которые FileDialog будет использовать для представления файловой системы |
Пример использования FileDialog с фильтрацией
В следующем коде формируется диалоговое окно выбора файла с использованием фильтра. Для подключения фильтра вызываются методы setFilterNames и setFilterExtensions. Описание расширений файлов для фильтра представлено в переменноЙ FILTERS.
Интерфейс диалогового окна выбора файла представлен на следующем скриншоте. Выпадающий список с фильтрами размещается в правом нижнем углу над кнопками управления.
В следующем примере для сохранения нового файла конструктору FileDialog передается опция SWT.SAVE.
Интерфейс диалогового окна сохранения файла представлен на следующем скриншоте. Выпадающий список с фильтрами размещается в нижней части под компонентом определения наименования файла.
При использования опции SWT.MULTI для работы с несколькими файлами одновременно необходимо при выделении очередного файла дополнительно удерживать в нажатом состоянии CTRL.
setFileView
@BeanProperty(preferred=true, description="Sets the File View used to get file type information.") public void setFileView ( FileView fileView)
Sets the file view to be used to retrieve UI information, such as the icon that represents a file or the type description of a file.
Swing включает мощное средство для работы с файлами — компонент JFileChooser —, представляющий контейнер, в котором расположены несколько компонентов, списков и кнопок, «управляющих» выбором файлов. JFileChooser можно добавить в любое место пользовательского интерфейса, поскольку это весьма гибкий компонент, позволяющий тонко настраивать внешний вид. При необходимости можно полностью изменить стандартное расположение входящих в JFileChooser компонентов и добавить дополнительные элементы, такие как панели предварительного просмотра файлов.
Все стандартные диалоговые окна Swing имеют собственные UI-представители, отвечающие за интерфейс окна в используемом приложении. Это особенно важно для внешних видов окон, имитирующих известные платформы, пользователи которых не должны ощущать значительной разницы при переходе от «родных» приложений к Java-приложения. UIManager позволяет выполнять настройку и локализацию интерфейса диалогового окна JFileChooser.
Начиная с выпуска JDK 1.3 библиотека Swing предлагает легко настраиваемый инструмент JFileChooser для выбора файлов и при необходимости каталогов. Особенности различных файловых систем скрыты в подклассах абстрактного класса FileSystemView, который представляет внешний вид файловой структуры согласно используемой операционной системе.
JFileChooser — это обычный компонент, унаследованный от класса JComponent, так что можно включить его в любое место интерфейса. Настроить и вывести на экран несложное диалоговое окно для открытия файла или сохранения в нем данных совсем легко.
Возвращаемые компонентом JFileChooser значения
- APPROVE_OPTION - выбор файла в диалоговом окне прошел успешно; выбранный файл можно получить методом getFile();
- CANCEL_OPTION - выбор файла отменен нажатием на кнопке Cancel;
- ERROR_OPTION - при выборе файла произошла ошибка, или было закрыто диалоговое окно выбора файла.
removeChoosableFileFilter
Removes a filter from the list of user choosable file filters. Returns true if the file filter was removed.
SAVE_DIALOG
showOpenDialog
Pops up an "Open File" file chooser dialog. Note that the text that appears in the approve button is determined by the L&F.
- JFileChooser.CANCEL_OPTION
- JFileChooser.APPROVE_OPTION
- JFileChooser.ERROR_OPTION if an error occurs or the dialog is dismissed
Fields inherited from class javax.swing.JComponent
Constructor Detail
JFileChooser
Constructs a JFileChooser pointing to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix.
JFileChooser
Constructs a JFileChooser using the given path. Passing in a null string causes the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix.
JFileChooser
Constructs a JFileChooser using the given File as the path. Passing in a null file causes the file chooser to point to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix.
JFileChooser
JFileChooser
JFileChooser
getApproveButtonText
Returns the text used in the ApproveButton in the FileChooserUI . If null , the UI object will determine the button's text. Typically, this would be "Open" or "Save".
DIALOG_TITLE_CHANGED_PROPERTY
JFileChooser
Constructs a JFileChooser pointing to the user's default directory. This default depends on the operating system. It is typically the "My Documents" folder on Windows, and the user's home directory on Unix.
Класс JOptionPane
Интерфейс экземпляра класса JOptionPane имеет структуру, представленную на следующем рисунке. Иконка в интерфейсе может отсутствовать.
Основные диалоговые методы JOptionPane
Конструкторы окна подтверждения showConfirmDialog
Конструкторы окна выбора showInputDialog
parent - родительское окно.
title - заголовок окна.
messageType - тип диалогового окна :
optionType - опция определения кнопок управления :
- DEFAULT_OPTION
- YES_NO_OPTION
- YES_NO_CANCEL_OPTION
- OK_CANCEL_OPTION
selectionValues - список возможных значений. В диалоговом окне InputDialog список будет представлен в компоненте JComboBox или JList. Если selectionValues = null, то в окне будет определено поле JTextField, в которое пользователь может ввести любое значение.
initialSelectionValue - инициализируемое значение.
icon - отображаемая в диалоговом окне иконка.
Локализация кнопок JOptionPane
Кнопки управления, как правило, имеют заголовки «Yes», «No», «Cancel». Для локализации кнопок диалогового компонента JOptionPane можно использовать UIManager следующим образом :
setSelectedFile
Sets the selected file. If the file's parent directory is not the current directory, changes the current directory to be the file's parent directory.
APPROVE_BUTTON_MNEMONIC_CHANGED_PROPERTY
getDialogType
- JFileChooser.OPEN_DIALOG
- JFileChooser.SAVE_DIALOG
- JFileChooser.CUSTOM_DIALOG
setMultiSelectionEnabled
@BeanProperty(description="Sets multiple file selection mode.") public void setMultiSelectionEnabled ( boolean b)
isDirectorySelectionEnabled
Convenience call that determines if directories are selectable based on the current file selection mode.
FILES_ONLY
Диалоговое окно DirectoryDialog
Конструкторы DirectoryDialog
Конструктор создания диалогового окна работы с директориями DirectoryDialog в качестве параметра принимает родительское окно parent. Второму конструктору дополнительно необходимо передать стиль style, который может принимать одно из значений [SWT.SAVE, SWT.OPEN].
Основные методы DirectoryDialog
Метод | Описание |
---|---|
String getFilterPath() | Функция получения выделенной в диалоговом окне DirectoryDialog директории |
String open() | Функция открытия диалогового окна DirectoryDialog и размещение его над всеми остальными окнами |
void setFilterPath(String string) | Функция определения директории, используемой DirectoryDialog для выделения |
Пример использования DirectoryDialog
В следующем примере формируется диалоговое окно выбора директории.
Интерфейс диалогового окна определения директории DirectoryDialog представлен на следующем скриншоте.
Диалоговое окно DirectoryDialog позволяет выполнять переименование директории и содержит кнопку «Создать папку», позволяющую создать новую директорию даже если была использована опция SWT.OPEN.
Диалоговые окна выбора данных InputDialog
Листинг процедуры создания слушателей, формирующие диалоговые окна выбора
Исходные коды примеров, рассмотренных на странице, можно скачать здесь (2.25 Кб).
JFileChooser provides a simple mechanism for the user to choose a file. For information about using JFileChooser , see How to Use File Choosers, a section in The Java Tutorial.
The following code pops up a file chooser for the user's home directory that sees only .jpg and .jpg images:
Warning: Swing is not thread safe. For more information see Swing's Threading Policy.
ACCESSORY_CHANGED_PROPERTY
Листинг метода addFileChooserListeners
В методе addFileChooserListeners() к каждой кнопке подключается свой слушатель, который формирует собственное диалоговое окно с определенными настройками.
Выбор директории
В коде определяется заголовок окна и режим открытия (JFileChooser.DIRECTORIES_ONLY). Интерфейс окна JFileChooser в режиме выбора директории представлен на следующем скриншоте.
Сохранение файла
В коде определяется заголовок окна и режим открытия (JFileChooser.FILES_ONLY). Интерфейс окна JFileChooser в режиме сохранения файла представлен на следующем скриншоте.
Использование фильтра
Покажем два способа подключения файлового фильтра. Первый способ - файловый фильтр можно создать и подключить к объекту JFileChooser с использованием класса FileNameExtensionFilter, пример использования которого представлен в следующем коде.
Второй способ - используем вспомогательный внутренний класс FileFilterExt, наследующий свойства класса FileFilter, в котором определяем два поля (расширение файлов extension, описание description) и переопределяем методы accept и getDescription.
В следующем коде слушателя выбора файла для кнопки btnFileFilter определяется заголовок окна, в цикле создаются экземпляры фильтров FileFilterExt, которые подключаются к fileChooser, и определяется режим открытия (JFileChooser.FILES_ONLY).
Интерфейс окна JFileChooser в режиме выбора файла с использованием файлового фильтра представлен на следующем скриншоте.
Исходные коды примеров, рассмотренных на странице, можно скачать здесь (2.20 Кб).
Класс Dialog бибилиотеки SWT является базовым классом следующих диалоговых окон :
SELECTED_FILES_CHANGED_PROPERTY
Methods declared in class java.lang.Object
setApproveButtonText
@BeanProperty(preferred=true, description="The text that goes in the ApproveButton.") public void setApproveButtonText ( String approveButtonText)
Nested Class Summary
addChoosableFileFilter
@BeanProperty(preferred=true, description="Adds a filter to the list of user choosable file filters.") public void addChoosableFileFilter ( FileFilter filter)
Adds a filter to the list of user choosable file filters. For information on setting the file selection mode, see setFileSelectionMode .
getApproveButtonMnemonic
Основные метод JFileChooser
Метод | Описание |
---|---|
File getCurrentDirectory() | Функция чтения текущей директории |
String getDialogTitle() | Функция чтения заголовка окна |
int getDialogType() | Функция чтения типа диалогового окна |
FileFilter getFileFilter() | Функция чтения текущего фильтра |
File getSelectedFile() | Функция чтения выделенного файла |
File[] getSelectedFiles() | Функция получения списка выделенных файлов, если установлен флаг выделения нескольких файлов MULTI_SELECTION_ENABLED_CHANGED_PROPERTY |
void setCurrentDirectory(File dir) | Метод определения текущей директории |
void setDialogTitle(String dialogTitle) | Метод определения заголовка диалогового окна |
void setDialogType(int dialogType) | Метод определения типа диалогового окна |
void setFileFilter(FileFilter filter) | Метод установки файлового фильтра |
void setFileSelectionMode(int mode) | Метод определения выделяемых объектов - файлы, директории или файлы с директориями |
void setMultiSelectionEnabled(boolean b) | Метод определения возможности выделения нескольких файлов |
void setSelectedFile(File file) | Метод выделения файла |
void setSelectedFiles(File[] selectedFiles) | Метод выделения списка файлов, если установлен флаг выделения нескольких файлов MULTI_SELECTION_ENABLED_CHANGED_PROPERTY |
int showDialog(Component parent, String approveButtonText) | Функция открытия окна выбора файла с настроенным наименованием кнопки |
int showOpenDialog(Component parent) | Функция открытия диалогового окна «Открыть файл» |
int showSaveDialog(Component parent) | Функция открытия диалогового окна «Сохранить файл» |
isAcceptAllFileFilterUsed
setDragEnabled
@BeanProperty(bound=false, description="determines whether automatic drag handling is enabled") public void setDragEnabled ( boolean b)
Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component. The transferHandler property needs to be set to a non- null value for the drag to do anything. The default value of the dragEnabled property is false .
When automatic drag handling is enabled, most look and feels begin a drag-and-drop operation whenever the user presses the mouse button over an item and then moves the mouse a few pixels. Setting this property to true can therefore have a subtle effect on how selections behave.
Some look and feels might not support automatic drag and drop; they will ignore this property. You can work around such look and feels by modifying the component to directly call the exportAsDrag method of a TransferHandler .
Пример использования JFileChooser
В примере FileChooserTest.java используется диалоговое окно выбора файла и директории с использованием компонента JFileChooser. Интерфейс окна включает 3 кнопки, по нажатию на которые открывается соответствующее диалоговое окно. Интерфейс главного окна представлен на следующем скриншоте.
Листинг примера JFileChooser
В примере определены кнопки, компонент выбора файла fileChooser и параметры файлового фильтра FILTERS. В конструкторе определяется интерфейс окна и вызывается метод addFileChooserListeners() для подключения к кнопкам слушателей.
Следует отметить, что компоненты диалогового окна локализованы с использованием метода put менеджера пользовательского интерфейса UIManager библиотеки Swing.
Режимы работы JFileChooser
Перед открытием диалогового окна для выбора файлов или директории необходимо определить режим работы JFileChooser. Компонент JFileChooser может работать в одном из трех режимов, который сохраняется в свойстве fileSelectionMode :
- FILES_ONLY - доступны только файлы, независимо от того, сохраняется файл или открывается. По умолчанию JFileChooser работает именно в этом режиме.
- FILES_AND_DIRECTORIES - доступны каталоги и файлы. Этот режим следует использовать только в том случае, когда необходимо поменять общие свойства файловой системы (файлы не отличаются от каталогов).
- DIRECTORIES_ONLY - доступны только каталоги.
Для определения режима используется метод setFileSelectionMode(mode).
getSelectedFiles
resetChoosableFileFilters
Resets the choosable file filter list to its starting state. Normally, this removes all added file filters while leaving the AcceptAll file filter.
Fields declared in interface java.awt.image.ImageObserver
CUSTOM_DIALOG
Field Summary
Identifies a change in the type of files displayed (files only, directories only, or both files and directories).
JFileChooser
setControlButtonsAreShown
@BeanProperty(preferred=true, description="Sets whether the approve & cancel buttons are shown.") public void setControlButtonsAreShown ( boolean b)
Sets the property that indicates whether the approve and cancel buttons are shown in the file chooser. This property is true by default. Look and feels that always show these buttons will ignore the value of this property. This method fires a property-changed event, using the string value of CONTROL_BUTTONS_ARE_SHOWN_CHANGED_PROPERTY as the name of the property.
ACCEPT_ALL_FILE_FILTER_USED_CHANGED_PROPERTY
Method Summary
Modifier and Type | Method and Description |
---|---|
boolean | accept (File f) |
Convenience call that determines if directories are selectable based on the current file selection mode.
Determines whether the AcceptAll FileFilter is used as an available choice in the choosable filter list.
Sets the property that indicates whether the approve and cancel buttons are shown in the file chooser.
Sets the dragEnabled property, which must be true to enable automatic drag handling (the first part of drag and drop) on this component.
Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories.
Sets the file system view that the JFileChooser uses for accessing and creating file system resources, such as finding the floppy drive and getting a list of root drives.
Sets the file view to used to retrieve UI information, such as the icon that represents a file or the type description of a file.
showSaveDialog
Pops up a "Save File" file chooser dialog. Note that the text that appears in the approve button is determined by the L&F.
- JFileChooser.CANCEL_OPTION
- JFileChooser.APPROVE_OPTION
- JFileChooser.ERROR_OPTION if an error occurs or the dialog is dismissed
Nested classes/interfaces declared in class java.awt.Container
ERROR_OPTION
Methods inherited from class javax.swing.JComponent
setFileSelectionMode
Sets the JFileChooser to allow the user to just select files, just select directories, or select both files and directories. The default is JFilesChooser.FILES_ONLY .
- JFileChooser.FILES_ONLY
- JFileChooser.DIRECTORIES_ONLY
- JFileChooser.FILES_AND_DIRECTORIES
getApproveButtonToolTipText
Returns the tooltip text used in the ApproveButton . If null , the UI object will determine the button's text.
accessibleContext
setApproveButtonMnemonic
Nested classes/interfaces declared in class javax.swing.JComponent
setApproveButtonMnemonic
@BeanProperty(preferred=true, description="The mnemonic key accelerator for the ApproveButton.") public void setApproveButtonMnemonic ( int mnemonic)
getSelectedFile
Returns the selected file. This can be set either by the programmer via setSelectedFile or by a user action, such as either typing the filename into the UI or selecting the file from a list in the UI.
Fields inherited from interface java.awt.image.ImageObserver
setAcceptAllFileFilterUsed
@BeanProperty(preferred=true, description="Sets whether the AcceptAll FileFilter is used as an available choice in the choosable filter list.") public void setAcceptAllFileFilterUsed ( boolean b)
Determines whether the AcceptAll FileFilter is used as an available choice in the choosable filter list. If false, the AcceptAll file filter is removed from the list of available file filters. If true, the AcceptAll file filter will become the actively used file filter.
Nested Class Summary
Modifier and Type | Class and Description |
---|---|
protected class | JFileChooser.AccessibleJFileChooser |
setFileFilter
@BeanProperty(preferred=true, description="Sets the File Filter used to filter out files of type.") public void setFileFilter ( FileFilter filter)
Sets the current file filter. The file filter is used by the file chooser to filter out files from the user's view.
Constructor Details
DIRECTORIES_ONLY
FILES_AND_DIRECTORIES
Fields declared in class javax.swing.JComponent
ensureFileIsVisible
OPEN_DIALOG
Methods inherited from class java.awt.Container
Конструкторы JFileChooser
Читайте также: