java filedialog

htt‮//:sp‬www.lautturi.com
java filedialog

To create a file dialog in Java, you can use the JFileChooser class. This class provides a simple, easy-to-use way to allow the user to select a file.

Here's an example of how to use JFileChooser to open a file dialog:

import javax.swing.JFileChooser;

public class Main {
  public static void main(String[] args) {
    JFileChooser fileChooser = new JFileChooser();
    int result = fileChooser.showOpenDialog(null);
    if (result == JFileChooser.APPROVE_OPTION) {
      // The user selected a file
      String filePath = fileChooser.getSelectedFile().getAbsolutePath();
      System.out.println("Selected file: " + filePath);
    }
  }
}

This code creates a new JFileChooser and opens a file dialog. If the user selects a file and clicks the "Open" button, the APPROVE_OPTION constant will be returned and the selected file's path will be printed to the console.

You can customize the file dialog by using various methods of the JFileChooser class, such as setDialogTitle(), setFileSelectionMode(), and setFileFilter(). You can also use showSaveDialog() to display a "Save" dialog instead of an "Open" dialog.

Created Time:2017-11-03 15:57:13  Author:lautturi