The documentation states:
The FileDialog class displays a dialog window from which the user can select a file.
Since it is a modal dialog, when the application calls its show method to display the dialog, it blocks the rest of the application until the user has chosen a file.
Therefore, instead of calling .setVisible(true)
you can call .show()
on the dialog, and then you can use getFile() to get the file that was chosen, or getFiles() if you are using multipleMode.
To read the file you can use:
public static String readFile(String path, Charset encoding) throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
yourComponent.setText(readFile(openf.getFile(), Charset.defaultCharset()));
(Taken from this question)