用Java怎么实现?
我想用Java做一个文件夹对话框,弹出该对话框后只能显示所选目录下的文件夹,选中某个文件夹,可以自动获取这个文件夹下所有文件(.txt)进行其他处理。请问应该怎么做?用什么类?
------解决方案--------------------JFileChooser
在jdk帮助中的例子如下:
JFileChooser chooser = new JFileChooser();
// Note: source for ExampleFileFilter can be found in FileChooserDemo,
// under the demo/jfc directory in the Java 2 SDK, Standard Edition.
ExampleFileFilter filter = new ExampleFileFilter();
filter.addExtension( "jpg ");
filter.addExtension( "gif ");
filter.setDescription( "JPG & GIF Images ");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println( "You chose to open this file: " +
chooser.getSelectedFile().getName());
}
------解决方案--------------------楼上正解
------解决方案--------------------给楼主一个程序和你的要求一样。
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.beans.*;
import java.util.*;
import java.io.*;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileView;
public class FileChooserTest
{
public static void main(String[] args)
{
ImageViewerFrame frame = new ImageViewerFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
/**
A frame that has a menu for loading an image and a display
area for the loaded image.
*/
class ImageViewerFrame extends JFrame
{
public ImageViewerFrame()
{
setTitle( "FileChooserTest ");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
// set up menu bar
JMenuBar menuBar = new JMenuBar();
setJMenuBar(menuBar);
JMenu menu = new JMenu( "File ");
menuBar.add(menu);
JMenuItem openItem = new JMenuItem( "Open ");
menu.add(openItem);
openItem.addActionListener(new FileOpenListener());
JMenuItem exitItem = new JMenuItem( "Exit ");
menu.add(exitItem);
exitItem.addActionListener(new
ActionListener()
{
public void actionPerformed(ActionEvent event)
{
System.exit(0);
}
});
// use a label to display the images
label = new JLabel();
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setVerticalAlignment(SwingConstants.CENTER);
add(label);
// set up file chooser
chooser = new JFileChooser();
// accept all image files ending with .jpg, .jpeg, .gif
final ExtensionFileFilter filter = new ExtensionFileFilter();
filter.addExtension( "jpg ");
filter.setDescription( "JPG格式图片 ");
filter.addExtension( "jpeg ");
filter.addExtension( "gif ");
filter.setDescription( "Image files ");
filter.setDescription( "JPG格式图片 ");
chooser.setFileFilter(filter);
chooser.setAccessory(new ImagePreviewer(chooser));
chooser.setFileView(new FileIconView(filter, new ImageIcon( "palette.gif ")));
}
/**
This is the listener for the File-> Open menu item.