SWT File Browser

This section illustrates you how to browse a file.
In SWT, the class FileDialog allow the user to navigate the file
system and select a file name. In order to layout the text, we have used the
method text.setLayoutData(data). The method file.isFile()
tests whether the file denoted by the pathname is a normal file. The method file.list()
returns an array of files and directories. The method text.setText(files[i])
sets the selected file in the text. The method text.setEditable(true)
sets the editable state.
Here is the code of FileBrowser.java
import java.io.File;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.*;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
public class FileBrowser {
Display display = new Display();
Shell shell = new Shell(display);
Text text;
public FileBrowser() {
init();
shell.pack();
shell.setSize(350,60);
shell.open();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
display.dispose();
}
private void init() {
shell.setText("File Browser");
shell.setLayout(new GridLayout(2, true));
GridData data = new GridData(GridData.FILL_BOTH);
text = new Text(shell, SWT.NONE);
text.setLayoutData(data);
Button button = new Button(shell, SWT.PUSH);
button.setText("Browse");
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
FileDialog dialog = new FileDialog(shell, SWT.NULL);
String path = dialog.open();
if (path != null) {
File file = new File(path);
if (file.isFile())
displayFiles(new String[] { file.toString()});
else
displayFiles(file.list());
}
}
});
}
public void displayFiles(String[] files) {
for (int i = 0; files != null && i < files.length; i++) {
text.setText(files[i]);
text.setEditable(true);
}
}
public static void main(String[] args) {
new FileBrowser();
}
}
|
Output will be displayed as:
On clicking the browse button, file dialog will open:
After clicking the open button, output will be displayed as:
Download Source code
