logo
down
shadow

Javafx filechooser name filter


Javafx filechooser name filter

Content Index :

Javafx filechooser name filter
Tag : java , By : unadopted
Date : December 05 2020, 12:23 PM

it fixes the issue Of course , you can get some idea from this example; in Java Swing( I'm not sure how in JavaFX) you can filter files by name or extension like :
FileChooser fileChooser = new FileChooser();
FileFilter filter = new FileNameExtensionFilter("MP3 File","mp3");
fileChooser.setFileFilter(filter)`

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

JavaFX FileChooser


Tag : development , By : meehan
Date : March 29 2020, 07:55 AM
I hope this helps . A DirectoryChooser was added to JavaFX as part of the 2.1 release. Usage is:
DirectoryChooser chooser = new DirectoryChooser();
chooser.setTitle("JavaFX Projects");
File defaultDirectory = new File("c:/dev/javafx");
chooser.setInitialDirectory(defaultDirectory);
File selectedDirectory = chooser.showDialog(primaryStage);

JavaFX FileChooser in swing


Tag : development , By : Kaputnik
Date : March 29 2020, 07:55 AM
this will help The code of that dialog has multiple problems besides the ones you mention. For example, it doesn't handle the situation when JavaFX platform shuts down right after isJavaFXStillUsable() is called, but before the call to Platform.runLater(), which will still make it hang forever. I don't like that huge synchronized block either, although there don't seem to be any real problems with that. I also don't get why "the stupid synchronization object had to be a field" - each invocation of chooseFileWithJavaFXDialog() is independent of each other, so it could just as well use a local final lock (even that array would do fine).
The right way to make JVM exit correctly is to call Platform.exit() when you are shutting down your application (perhaps in windowClosed() of your main window). You need to do this manually because the chooser class has no idea whether you need JavaFX any more or not, and there is no way to restart it once it has been shut down.
/**
 * A utility class to execute a Callable synchronously
 * on the JavaFX event thread.
 * 
 * @param <T> the return type of the callable
 */
public class SynchronousJFXCaller<T> {
    private final Callable<T> callable;

    /**
     * Constructs a new caller that will execute the provided callable.
     * 
     * The callable is accessed from the JavaFX event thread, so it should either
     * be immutable or at least its state shouldn't be changed randomly while
     * the call() method is in progress.
     * 
     * @param callable the action to execute on the JFX event thread
     */
    public SynchronousJFXCaller(Callable<T> callable) {
        this.callable = callable;
    }

    /**
     * Executes the Callable.
     * <p>
     * A specialized task is run using Platform.runLater(). The calling thread
     * then waits first for the task to start, then for it to return a result.
     * Any exception thrown by the Callable will be rethrown in the calling
     * thread.
     * </p>
     * @param startTimeout time to wait for Platform.runLater() to <em>start</em>
     * the dialog-showing task
     * @param startTimeoutUnit the time unit of the startTimeout argument
     * @return whatever the Callable returns
     * @throws IllegalStateException if Platform.runLater() fails to start
     * the task within the given timeout
     * @throws InterruptedException if the calling (this) thread is interrupted
     * while waiting for the task to start or to get its result (note that the
     * task will still run anyway and its result will be ignored)
     */
    public T call(long startTimeout, TimeUnit startTimeoutUnit)
            throws Exception {
        final CountDownLatch taskStarted = new CountDownLatch(1);
        // Can't use volatile boolean here because only finals can be accessed
        // from closures like the lambda expression below.
        final AtomicBoolean taskCancelled = new AtomicBoolean(false);
        // a trick to emulate modality:
        final JDialog modalBlocker = new JDialog();
        modalBlocker.setModal(true);
        modalBlocker.setUndecorated(true);
        modalBlocker.setOpacity(0.0f);
        modalBlocker.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        final CountDownLatch modalityLatch = new CountDownLatch(1);
        final FutureTask<T> task = new FutureTask<T>(() -> {
            synchronized (taskStarted) {
                if (taskCancelled.get()) {
                    return null;
                } else {
                    taskStarted.countDown();
                }
            }
            try {
                return callable.call();
            } finally {
                // Wait until the Swing thread is blocked in setVisible():
                modalityLatch.await();
                // and unblock it:
                SwingUtilities.invokeLater(() ->
                        modalBlocker.setVisible(false));
            }
        });
        Platform.runLater(task);
        if (!taskStarted.await(startTimeout, startTimeoutUnit)) {
            synchronized (taskStarted) {
                // the last chance, it could have been started just now
                if (!taskStarted.await(0, TimeUnit.MILLISECONDS)) {
                    // Can't use task.cancel() here because it would
                    // interrupt the JavaFX thread, which we don't own.
                    taskCancelled.set(true);
                    throw new IllegalStateException("JavaFX was shut down"
                            + " or is unresponsive");
                }
            }
        }
        // a trick to notify the task AFTER we have been blocked
        // in setVisible()
        SwingUtilities.invokeLater(() -> {
            // notify that we are ready to get the result:
            modalityLatch.countDown();
        });
        modalBlocker.setVisible(true); // blocks
        modalBlocker.dispose(); // release resources
        try {
            return task.get();
        } catch (ExecutionException ex) {
            Throwable ec = ex.getCause();
            if (ec instanceof Exception) {
                throw (Exception) ec;
            } else if (ec instanceof Error) {
                throw (Error) ec;
            } else {
                throw new AssertionError("Unexpected exception type", ec);
            }
        }
    }

}
/**
 * A utility class that summons JavaFX FileChooser from the Swing EDT.
 * (Or anywhere else for that matter.) JavaFX should be initialized prior to
 * using this class (e. g. by creating a JFXPanel instance). It is also
 * recommended to call Platform.setImplicitExit(false) after initialization
 * to ensure that JavaFX platform keeps running. Don't forget to call
 * Platform.exit() when shutting down the application, to ensure that
 * the JavaFX threads don't prevent JVM exit.
 */
public class SynchronousJFXFileChooser {
    private final Supplier<FileChooser> fileChooserFactory;

    /**
     * Constructs a new file chooser that will use the provided factory.
     * 
     * The factory is accessed from the JavaFX event thread, so it should either
     * be immutable or at least its state shouldn't be changed randomly while
     * one of the dialog-showing method calls is in progress.
     * 
     * The factory should create and set up the chooser, for example,
     * by setting extension filters. If there is no need to perform custom
     * initialization of the chooser, FileChooser::new could be passed as
     * a factory.
     * 
     * Alternatively, the method parameter supplied to the showDialog()
     * function can be used to provide custom initialization.
     * 
     * @param fileChooserFactory the function used to construct new choosers
     */
    public SynchronousJFXFileChooser(Supplier<FileChooser> fileChooserFactory) {
        this.fileChooserFactory = fileChooserFactory;
    }

    /**
     * Shows the FileChooser dialog by calling the provided method.
     * 
     * Waits for one second for the dialog-showing task to start in the JavaFX
     * event thread, then throws an IllegalStateException if it didn't start.
     * 
     * @see #showDialog(java.util.function.Function, long, java.util.concurrent.TimeUnit) 
     * @param <T> the return type of the method, usually File or List&lt;File&gt;
     * @param method a function calling one of the dialog-showing methods
     * @return whatever the method returns
     */
    public <T> T showDialog(Function<FileChooser, T> method) {
        return showDialog(method, 1, TimeUnit.SECONDS);
    }

    /**
     * Shows the FileChooser dialog by calling the provided method. The dialog 
     * is created by the factory supplied to the constructor, then it is shown
     * by calling the provided method on it, then the result is returned.
     * <p>
     * Everything happens in the right threads thanks to
     * {@link SynchronousJFXCaller}. The task performed in the JavaFX thread
     * consists of two steps: construct a chooser using the provided factory
     * and invoke the provided method on it. Any exception thrown during these
     * steps will be rethrown in the calling thread, which shouldn't
     * normally happen unless the factory throws an unchecked exception.
     * </p>
     * <p>
     * If the calling thread is interrupted during either the wait for
     * the task to start or for its result, then null is returned and
     * the Thread interrupted status is set.
     * </p>
     * @param <T> return type (usually File or List&lt;File&gt;)
     * @param method a function that calls the desired FileChooser method
     * @param timeout time to wait for Platform.runLater() to <em>start</em>
     * the dialog-showing task (once started, it is allowed to run as long
     * as needed)
     * @param unit the time unit of the timeout argument
     * @return whatever the method returns
     * @throws IllegalStateException if Platform.runLater() fails to start
     * the dialog-showing task within the given timeout
     */
    public <T> T showDialog(Function<FileChooser, T> method,
            long timeout, TimeUnit unit) {
        Callable<T> task = () -> {
            FileChooser chooser = fileChooserFactory.get();
            return method.apply(chooser);
        };
        SynchronousJFXCaller<T> caller = new SynchronousJFXCaller<>(task);
        try {
            return caller.call(timeout, unit);
        } catch (RuntimeException | Error ex) {
            throw ex;
        } catch (InterruptedException ex) {
            Thread.currentThread().interrupt();
            return null;
        } catch (Exception ex) {
            throw new AssertionError("Got unexpected checked exception from"
                    + " SynchronousJFXCaller.call()", ex);
        }
    }

    /**
     * Shows a FileChooser using FileChooser.showOpenDialog().
     * 
     * @see #showDialog(java.util.function.Function, long, java.util.concurrent.TimeUnit) 
     * @return the return value of FileChooser.showOpenDialog()
     */
    public File showOpenDialog() {
        return showDialog(chooser -> chooser.showOpenDialog(null));
    }

    /**
     * Shows a FileChooser using FileChooser.showSaveDialog().
     * 
     * @see #showDialog(java.util.function.Function, long, java.util.concurrent.TimeUnit) 
     * @return the return value of FileChooser.showSaveDialog()
     */
    public File showSaveDialog() {
        return showDialog(chooser -> chooser.showSaveDialog(null));
    }

    /**
     * Shows a FileChooser using FileChooser.showOpenMultipleDialog().
     * 
     * @see #showDialog(java.util.function.Function, long, java.util.concurrent.TimeUnit) 
     * @return the return value of FileChooser.showOpenMultipleDialog()
     */
    public List<File> showOpenMultipleDialog() {
        return showDialog(chooser -> chooser.showOpenMultipleDialog(null));
    }

    public static void main(String[] args) {
        javafx.embed.swing.JFXPanel dummy = new javafx.embed.swing.JFXPanel();
        Platform.setImplicitExit(false);
        try {
            SynchronousJFXFileChooser chooser = new SynchronousJFXFileChooser(() -> {
                FileChooser ch = new FileChooser();
                ch.setTitle("Open any file you wish");
                return ch;
            });
            File file = chooser.showOpenDialog();
            System.out.println(file);
            // this will throw an exception:
            chooser.showDialog(ch -> ch.showOpenDialog(null), 1, TimeUnit.NANOSECONDS);
        } finally {
            Platform.exit();
        }
    }

}
    System.out.println(chooser.showDialog(ch -> {
        ch.setInitialDirectory(new File(System.getProperty("user.home")));
        return ch.showOpenDialog(null);
    }));

JavaFX FileChooser new file


Tag : java , By : pepper
Date : March 29 2020, 07:55 AM
it fixes the issue Yes that should be possible, you just need to know the right function to call. The API for FileChooser details them in its opening paragraph here.
    FileChooser fileChooser = new FileChooser();
    File selectedFile = fileChooser.showSaveDialog(null);
    FileChooser fileChooser = new FileChooser();
    File selectedFile = fileChooser.showOpenDialog(null);
    FileChooser fileChooser = new FileChooser();
    List<File> files = fileChooser.showOpenMultipleDialog(null); 

javafx.stage.FileChooser


Tag : java , By : Ir0nh1de
Date : March 29 2020, 07:55 AM

JavaFx FileChooser without Stage


Tag : java , By : DK.
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • How to configure java.util.logging via properties to use standard output?
  • How to iterate through array in order
  • Is there better way of iteration to find the evenly divisible number?
  • How do I avoid using if statements with a large amount of variables in java
  • Writing JUnit test cases for a Spring Boot Service Application with autowired components
  • Cors for GET with Postman not showing headers
  • Printing values in different column same row using APACHE POI
  • Fully decompile java6 web application
  • Passing keycloak configuration parameters in the code rather than reading from application.properties
  • setDataSource() IO exception
  • Unexpected Output while retrieving Data from mongodb and displaying in a csv file?
  • Algorithm for searching a value in two arrays
  • How to avoid casting with generic return values?
  • Java/RegEx - Negation of pattern not working
  • How to split a string to non empty words if it might include a separator like tab on first place
  • Supplier<Sequence<String>> cannot be iterated more than once
  • Why there is only one thread can actually started in @PostConstruct method?
  • Manage CompletionStage inside of Netty handler
  • Url Problem while Developing on Localhost and deploy on Remote Virtual Server
  • How to identify the missing type id in Jackson error?
  • android data binding error: cannot find symbol
  • Spring Boot application with a jar dependency does not run after maven build
  • Spring Data JPA query , filter ? search engine ? JPQL?
  • Why LiveData returns null in ViewModel?
  • what this line of code mean....new URLClassLoader(new URL[0],getClass().getClassLoader());
  • Why do need to use new Random() instead of just Random Randomnum?
  • I want to access zk components from the java file
  • How do I cast FieldValue.serverTimestamp() to Kotlin/Java Date Class
  • Insertion Sort Double Array with User Input - JAVA
  • Creating 2 dimesional array with user input and find sum of specific columns
  • can not get Advertising ID Provider in android
  • Convert list of Objects to map of properties
  • How to represent an undirected weighted graph in java
  • Return values as array from collection
  • ByteBuddy generic method return cast to concrete type
  • ImageView hides the round corners of the parent
  • Is there a way to find setter method by its getter method or vice versa in a class?
  • Get aggregated list of properties from list of Objects(Java 8)
  • Unable to find a document in Mongodb where exact date match in java
  • UsernamePasswordAuthenticationFilter skips success handler
  • Use Java filter on stream with in a stream filter
  • Default Login not successful in spring boot 2.1.7
  • Adding key value pairs from a file to a Hashmap
  • Rub regex: matching a char except when after by another char
  • Convert Base64 String to String Array
  • Escape Unicode Character 'POPCORN' to HTML Entity
  • An empty JSON field which is a boolean/nullable field in Java model, is getting converted as null
  • Mongo java driver cannot find public constructor for interface
  • How to unit test writing a file to AWS Lambda output stream?
  • How to make a GitHub GraphQL API Call from Java
  • What's the difference between @ComponentScan and @Bean in a context configuration?
  • Expected class or package adding a view using a class
  • can be delete of a element in a static array be O(1)?
  • Instance variable heap or stack ? ( with specific example)
  • Assert progress of ProgressBar in Espresso test
  • How to detect if gson.fromjson() has excess elements
  • I cant generate the proper code to select the a specific filter on a BI dashboard I am working on
  • How to Inject Dependencies into a Servlet Filter with Spring Boot Filter Registration Bean?
  • Thrift types as a Generic
  • Effective algorithm to random 4 unique integers less than a big max such as 100_000
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com