文件选择
一个SWT文件,实现选择文件,显示文件功能,代码和实现的结果如下:

FileSelection
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.*;

public class FileSelection


{
Display display = new Display();
Shell shell = new Shell();
Label fileLabel;
Button selectFileButton;
String filePath = "c:\\";
public FileSelection()

{
fileLabel = new Label(shell,SWT.BORDER|SWT.WRAP);
fileLabel.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
fileLabel.setText("选择文件");
selectFileButton = new Button(shell,SWT.PUSH);
selectFileButton.setText("请选择文件");

selectFileButton.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event event)

{
FileDialog fileDialog = new FileDialog(shell,SWT.MULTI);
fileDialog.setFilterPath(filePath);

fileDialog.setFilterExtensions(new String[]
{"*.txt","*.html","*.*"});

fileDialog.setFilterNames(new String[]
{"文本文件","HTML文件","任何"});
String firstFile = fileDialog.open();
if(firstFile!=null)

{
filePath = fileDialog.getFilterPath();
String selectedFiles[] = fileDialog.getFileNames();
StringBuffer sb = new StringBuffer("你选择了如下的文件"
+fileDialog.getFilterPath()+"\\ \n");
for(int i=0; i<selectedFiles.length;i++)

{
sb.append(selectedFiles[i]+"\n");
}
fileLabel.setText(sb.toString());
}
}
});
fileLabel.setBounds(0,0,400,100);
selectFileButton.setBounds(100,110,200,25);
shell.pack();
shell.open();
while(!shell.isDisposed())

{
if(!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public static void main(String args[])

{
new FileSelection();
}
}
运行结果:

根据路径打开文件:

显示选中的文件:

import org.eclipse.swt.widgets.*;
import org.eclipse.swt.*;
public class FileSelection 

{
Display display = new Display();
Shell shell = new Shell();
Label fileLabel;
Button selectFileButton;
String filePath = "c:\\";
public FileSelection()
{
fileLabel = new Label(shell,SWT.BORDER|SWT.WRAP);
fileLabel.setBackground(display.getSystemColor(SWT.COLOR_WHITE));
fileLabel.setText("选择文件");
selectFileButton = new Button(shell,SWT.PUSH);
selectFileButton.setText("请选择文件");

selectFileButton.addListener(SWT.Selection, new Listener()
{
public void handleEvent(Event event)
{
FileDialog fileDialog = new FileDialog(shell,SWT.MULTI);
fileDialog.setFilterPath(filePath);
fileDialog.setFilterExtensions(new String[]
{"*.txt","*.html","*.*"});
fileDialog.setFilterNames(new String[]
{"文本文件","HTML文件","任何"});
String firstFile = fileDialog.open();
if(firstFile!=null)
{
filePath = fileDialog.getFilterPath();
String selectedFiles[] = fileDialog.getFileNames();
StringBuffer sb = new StringBuffer("你选择了如下的文件"
+fileDialog.getFilterPath()+"\\ \n");
for(int i=0; i<selectedFiles.length;i++)
{
sb.append(selectedFiles[i]+"\n");
}
fileLabel.setText(sb.toString());
}
}
});
fileLabel.setBounds(0,0,400,100);
selectFileButton.setBounds(100,110,200,25);
shell.pack();
shell.open();
while(!shell.isDisposed())
{
if(!display.readAndDispatch())
display.sleep();
}
display.dispose();
}
public static void main(String args[])
{
new FileSelection();
}
}

根据路径打开文件:

显示选中的文件:

浙公网安备 33010602011771号