Save to file java swing

Swing Examples — Show Save File Dialog

Following example showcase how to create and show a save as file dialog in swing based application.

We are using the following APIs.

  • JFileChooser − To create a standard File chooser which allows user to save file/Folders.
  • JFileChooser.showSaveDialog − To show the Save As dialog box.

Example

import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.LayoutManager; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class SwingTester < public static void main(String[] args) < createWindow(); >private static void createWindow() < JFrame frame = new JFrame("Swing Tester"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); createUI(frame); frame.setSize(560, 200); frame.setLocationRelativeTo(null); frame.setVisible(true); >private static void createUI(final JFrame frame)< JPanel panel = new JPanel(); LayoutManager layout = new FlowLayout(); panel.setLayout(layout); JButton button = new JButton("Click Me!"); final JLabel label = new JLabel(); button.addActionListener(new ActionListener() < @Override public void actionPerformed(ActionEvent e) < JFileChooser fileChooser = new JFileChooser(); int option = fileChooser.showSaveDialog(frame); if(option == JFileChooser.APPROVE_OPTION)< File file = fileChooser.getSelectedFile(); label.setText("File Saved as: " + file.getName()); >else < label.setText("Save command canceled"); >> >); panel.add(button); panel.add(label); frame.getContentPane().add(panel, BorderLayout.CENTER); > >

Output

Show Save File Dialog

Источник

Show save file dialog using JFileChooser

Swing provides class javax.swing.JFileChooser that can be used to present a dialog for user to choose a location and type a file name to be saved, using showSaveDialog() method. Syntax of this method is as follows:

Читайте также:  Цвета

public int showSaveDialog( Component parent)

where parent is the parent component of the dialog, such as a JFrame . Once the user typed a file name and select OK or Cancel, the method returns one of the following value:

    • JFileChooser.CANCEL_OPTION : the user cancels file selection.
    • JFileChooser.APPROVE_OPTION : the user accepts file selection.
    • JFileChooser.ERROR_OPTION : if there’s an error or the user closes the dialog by clicking on X button.

    After the dialog is dismissed and the user approved a selection, use the following methods to get the selected file:

    Before calling showSaveDialog() method, you may want to set some options for the dialog:

      • setDialogTitle ( String) sets a custom title text for the dialog.
      • setCurrentDirectory ( File) sets the directory where will be saved.

      Following is an example code:

      // parent component of the dialog JFrame parentFrame = new JFrame(); JFileChooser fileChooser = new JFileChooser(); fileChooser.setDialogTitle(«Specify a file to save»); int userSelection = fileChooser.showSaveDialog(parentFrame); if (userSelection == JFileChooser.APPROVE_OPTION)

      And following is a screenshot of the dialog:

      save file dialog

      You can download a fully working example code in the attachment section.

      Other Java Swing Tutorials:

      About the Author:

      Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

      Источник

      Java Swing How to — Make JFileChooser to save file

      We would like to know how to make JFileChooser to save file.

      Answer

      import java.awt.BorderLayout; import java.awt.Desktop; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStreamWriter; /*from w w w . j a v a2s . co m*/ import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; public class Main < JTextArea textArea; JButton save; void initUI() < JFrame frame = new JFrame(Main.class.getSimpleName()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); textArea = new JTextArea(24, 80); save = new JButton("Save to file"); save.addActionListener(e -> saveToFile()); frame.add(new JScrollPane(textArea)); JPanel buttonPanel = new JPanel(); buttonPanel.add(save); frame.add(buttonPanel, BorderLayout.SOUTH); frame.setSize(500, 400); frame.setVisible(true); > protected void saveToFile() < JFileChooser fileChooser = new JFileChooser(); int retval = fileChooser.showSaveDialog(save); if (retval == JFileChooser.APPROVE_OPTION) < File file = fileChooser.getSelectedFile(); if (file == null) < return; > if (!file.getName().toLowerCase().endsWith(".txt")) < file = new File(file.getParentFile(), file.getName() + ".txt"); > try < textArea.write(new OutputStreamWriter(new FileOutputStream(file), "utf-8")); Desktop.getDesktop().open(file); > catch (Exception e) < e.printStackTrace(); >> > public static void main(String[] args) < new Main().initUI(); > >

      java2s.com | © Demo Source and Support. All rights reserved.

      Источник

      Java Swing — пример JFileChooser

      JFileChooser это быстрый и простой способ предложить пользователю выбрать файл или место сохранения файла. Ниже приведены несколько простых примеров использования этого класса.

      JFileChooser имеет 6 конструкторов:

      • JFileChooser() — пустой конструктор, который указывает на каталог пользователя по умолчанию
      • JFileChooser(String) — использует заданный путь
      • JFileChooser(File) — использует данный файл в качестве пути
      • JFileChooser(FileSystemView) — использует данный FileSystemView
      • JFileChooser(String, FileSystemView) — использует заданный путь и FileSystemView
      • JFileChooser(File, FileSystemView) — использует данный текущий каталог и FileSystemView

      Все разные способы вызова JFileChooser конструктор

       // JFileChooser jfc; // String path = "C: Users Public"; // File file = new File ("C: Users Public"); // FileSystemView fsv = FileSystemView.getFileSystemView (); // jfc = new JFileChooser (); // jfc = new JFileChooser (path); // jfc = new JFileChooser (file); // jfc = new JFileChooser (fsv); // jfc = new JFileChooser (path, fsv); // jfc = new JFileChooser (file, fsv); 

      Личное предпочтение автора должно принимать во внимание FileSystemView , В приведенных ниже примерах мы используем FileSystemView.getFileSystemView() и указать его в домашний каталог через getHomeDirectory() , Этот процесс приводит к типу файла. Другими словами, мы используем конструктор JFileChooser(File) принимая во внимание FileSystemView ,

      1. show * Dialog () — Открыть или сохранить файл

      Пример использования JFileChooser чтобы получить абсолютный путь к файлу, который пользователь хочет открыть, или получить местоположение, где пользователь хочет сохранить файл:

       package com.csharpcoderr.jfileChooser; import java.io.File; import javax.swing.JFileChooser; import javax.swing.filechooser.FileSystemView; public class FileChooser1 < public static void main(String[] args) < JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); int returnValue = jfc.showOpenDialog(null); // int returnValue = jfc.showSaveDialog (null); if (returnValue == JFileChooser.APPROVE_OPTION) < File selectedFile = jfc.getSelectedFile(); System.out.println(selectedFile.getAbsolutePath()); >> > 

      Обратите внимание, что два метода showOpenDialog() а также showSaveDialog() похожи, что делает разницу в том, как разработчик обрабатывает каждый из них. Для удобства чтения я бы не советовал смешивать два метода.

      Когда пользователь переходит в каталог, выбирает файл и нажимает «Открыть».

       C:UsersPublicPicturespollock.she-wolf.jpg 

      2. setFileSelectionMode (int) — Выбрать файлы или каталоги

      С помощью этого метода мы можем ограничить выбор пользователем только каталогов ( JFileChooser.DIRECTORIES_ONLY ) или только файлы ( JFileChooser.FILES_ONLY ) или файлы и каталоги ( JFileChooser.FILES_AND_DIRECTORIES ). По умолчанию FILES_ONLY , Вот пример, который реализует JFileChooser.DIRECTORIES_ONLY :

       package com.csharpcoderr.jfileChooser; import javax.swing.JFileChooser; import javax.swing.filechooser.FileSystemView; public class FileChooser2 < public static void main(String[] args) < JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory()); jfc.setDialogTitle("Choose a directory to save your file: "); jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnValue = jfc.showSaveDialog(null); if (returnValue == JFileChooser.APPROVE_OPTION) < if (jfc.getSelectedFile().isDirectory()) < System.out.println("You selected the directory: " + jfc.getSelectedFile()); >> > > 

      Источник

Оцените статью