ncuccia
ncuccia

Reputation: 305

Selecting a file in Explorer for use in Java

I am trying to write a program that will make a copy of a preexisting file in the same directory with a different name for the new file. I have already programmed all the 'behind the scenes' actions of the file copy. What I want to do now is make it so that when the program is launched, a windows explorer dialog window pops up and asks to select the original file to be copied. How would I go about doing this?

Upvotes: 0

Views: 527

Answers (3)

Vallabh Patade
Vallabh Patade

Reputation: 5110

You need to use JFileChooser class. It's a class included in JDK. No need to have any third part library.

You can find a simple example here

Upvotes: 0

hmnbvcxz
hmnbvcxz

Reputation: 56

In Java Swing, use a "File chooser."

If you need it, I can type up an example.

Upvotes: 1

Dmitry Ginzburg
Dmitry Ginzburg

Reputation: 7461

You should consider creating the JavaFX application. It's included in modern Java distributions. Just look at the docs. For example, that would be something like

package blahblah;

import java.io.File;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

public class BlahBlah extends Application {

    @Override
    public void start(Stage primaryStage) {
        StackPane root = new StackPane();

        // add some elements to root

        FileChooser fileChooser = new FileChooser();
        File file = fileChooser.showOpenDialog(primaryStage);
        //for example:
        System.out.println("File chosen: " + file.getAbsolutePath());

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

Upvotes: 0

Related Questions