文件对话框

1,Swing提供了JFileChoose类,特可以显示一个文件对话框。


2,JFileChoose类并不是JDialog类的子类。需要调用showOpenDialog,而不是调用setVisibel(true)来显示打开文件的对话框,或者调用showSaveDialog显示保存文件的对话框。接收文件的按钮被标签为Open或者Save,也可以调用showDialog方法制定自己的标签。


3,调用showOpenDialog或者showSaveDialog方法显示对话框。必须为这些调用提供父组件:

Int result = chooser.showOepnDialog(parent);

或者

Int result = chooser.showSaveDialog(parent);

这些调用的区别就是“确认按钮”的标签不同,点击“确认按钮”完成文件选择。也可以调用showDialog方法并将一个显示的文本传递个确认按钮。

Int result = chooser.showDialog(parent,”select”);

仅当用户确认、取消或者离开文件对话框时才返回调用。返回值可以是JFileChoose.APPROVE_OPEION,JFileChooser.CANCLE_OPTION或者JFileChooser.ERROR_OPTION。


4,若想限制显示的文件,需要创建扩展了抽象类javax.swing.filechooser.FileFilter的对象。文件选择器把每个文件传递个过滤器,只有文件过滤器接受的文件才被最终显示出来。编写专用文件过滤器非常简单,只要事先FileFilter子类中的两个抽象方法即可:

Public boolean accept(File f);

Public String getDescription();

第一个方法测试是否应该接受一个文件。第二个方法返回显示在文件选择器对话框中的文件类型的说明信息。例如,如果值选择GIF文件,可以使用下面的代码:

Public clas GifFilter extends FileFilter

{

Public boolean accept(File f)

{

Return f.getName().toLowerCase().endsWith(“.gif”)||f.isDirectory();

}

Public String getDescription()

{

Return “GIF Image”;

}

}

一旦有个文件过滤对象,就可以使用JFileChoose类的setFileFilter方法,将这个对象安装到文件选择器对象中:

chooser.setFileFilter(new GifFilter());

在市里程序中,提供了一个ExtensionFileFilter类,其用法如下:

ExtensionFileFilter filter = new ExtensionFileFilter();

filter.addExtension(“jpg”);

filter.addExtension(“gif”);

filter.setDescription(“image files”);

ExrensionFileFilter类的事先不过是对GifFilter类的一个简要总结。可以在自己的程序中使用这个类。


5,通过添加对文件选择器显示的每个文件的特殊图标和文件说明来定制自己的文件选择器。这需要扩展javax.swing.filechooser包中的FileView类。这是一项高级的技巧。在通常情况下,不需要提供文件视图——可插观感会提供。但是如果想为特殊的文件类型显示不同的图标,就需要安装自己的文件视图。这要扩展FileView并实现下面5个方法:

Icon getIcon(File f);

String getName(File f);

String getDescription(File f);

String getTypeDescription(File f);

Boolean isTraversable(File f);

然后,使用setFileView方法将文件视图安装到文件选择器中。

使用setFileView方法可以将文件视图安装到文件选择器中:

chooser.setFileView(new FileIconView(filter,new ImageIcon(“palette.gif”)));

例子:

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();
      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.addExtension("jpeg");
      filter.addExtension("gif");
      filter.setDescription("Image files");
      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.
   */
   private class FileOpenListener implements ActionListener
   {
      public void actionPerformed(ActionEvent event)
      {
         chooser.setCurrentDirectory(new File("."));

         // show file chooser dialog
         int result = chooser.showOpenDialog(ImageViewerFrame.this);

         // if image file accepted, set it as icon of the label
         if(result == JFileChooser.APPROVE_OPTION)
         {
            String name = chooser.getSelectedFile().getPath();
            label.setIcon(new ImageIcon(name));
         }
      }
   }

   public static final int DEFAULT_WIDTH = 300;
   public static final int DEFAULT_HEIGHT = 400;  

   private JLabel label;
   private JFileChooser chooser;
}

/**
   This file filter matches all files with a given set of 
   extensions.
*/
class ExtensionFileFilter extends FileFilter
{
   /**
      Adds an extension that this file filter recognizes.
      @param extension a file extension (such as ".txt" or "txt")
   */
   public void addExtension(String extension)
   {
      if (!extension.startsWith("."))
         extension = "." + extension;
      extensions.add(extension.toLowerCase());     
   }

   /**
      Sets a description for the file set that this file filter
      recognizes.
      @param aDescription a description for the file set
   */
   public void setDescription(String aDescription)
   {
      description = aDescription;
   }

   /**
      Returns a description for the file set that this file
      filter recognizes.
      @return a description for the file set
   */
   public String getDescription()
   {
      return description; 
   }

   public boolean accept(File f)
   {
	    //isDirectory
	    //public boolean isDirectory()
		//测试此抽象路径名表示的文件是否是一个目录。
		//返回:
		//		当且仅当此抽象路径名表示的文件存在且 是一个目录时,返回 true;否则返回 false
		//抛出:
		//		SecurityException - 如果存在安全管理器,且其 SecurityManager.checkRead(java.lang.String) 方法拒绝对文件进行读访问

      if (f.isDirectory()) return true;
      String name = f.getName().toLowerCase();

      // check if the file name ends with any of the extensions
      for (String extension : extensions)
         if (name.endsWith(extension)) 
            return true;
      return false;
   }
   
   private String description = "";
   private ArrayList<String> extensions = new ArrayList<String>();
}

/**
   A file view that displays an icon for all files that match
   a file filter.
   文件视图类。当文件匹配文件过滤器时,该类就会显示一个特殊的图标。
   可以使用这个类为所有图像文件显示一个调色图标。
*/
class FileIconView extends FileView
{
   /** 
       Constructs a FileIconView.
       @param aFilter a file filter--all files that this filter
       accepts will be shown with the icon.
       @param anIcon--the icon shown with all accepted files.
   */
   public FileIconView(FileFilter aFilter, Icon anIcon)
   {
      filter = aFilter;
      icon = anIcon;
   }

   public Icon getIcon(File f)
   {
      if (!f.isDirectory() && filter.accept(f)) 
         return icon;
      else return null;
   }
   
   private FileFilter filter;
   private Icon icon;
}

/**
   A file chooser accessory that previews images.
*/
class ImagePreviewer extends JLabel 
{
   /**
      Constructs an ImagePreviewer.
      @param chooser the file chooser whose property changes
      trigger an image change in this previewer
            用户选择不用 的文件时更新预览头像
   */
   public ImagePreviewer(JFileChooser chooser) 
   {
      setPreferredSize(new Dimension(100, 100));
      setBorder(BorderFactory.createEtchedBorder());

      chooser.addPropertyChangeListener(new 
         PropertyChangeListener()
         {
            public void propertyChange(PropertyChangeEvent event) 
            {
               if (event.getPropertyName() ==
                  JFileChooser.SELECTED_FILE_CHANGED_PROPERTY)
               {
                  // the user has selected a new file 
                  File f = (File) event.getNewValue();
                  if (f == null) { setIcon(null); return; }
                  
                  // read the image into an icon
                  ImageIcon icon = new ImageIcon(f.getPath());

                  // if the icon is too large to fit, scale it
                  if(icon.getIconWidth() > getWidth())
                     icon = new ImageIcon(icon.getImage().getScaledInstance(
                        getWidth(), -1, Image.SCALE_DEFAULT));

                  setIcon(icon);
               }
	    }
         });
   }
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
wxWidgets是一个开源的C++图形用户界面库,它提供了跨平台的GUI解决方案。其中的文件对话框是wxWidgets提供的一个常用的对话框类。 文件对话框主要用于打开和保存文件操作。通过文件对话框,我们可以与用户交互并选择需要操作的文件路径和文件名。在wxWidgets中,可以使用wxFileDialog类来创建和使用文件对话框。 首先,我们需要创建一个wxFileDialog实例,并指定对话框的父窗口、标题、默认路径等属性。然后,可以通过调用ShowModal()函数来显示文件对话框,并等待用户操作。 用户在文件对话框中可以选择文件路径和名称,并进行打开或保存操作。如果用户点击了打开或保存按钮,我们可以调用GetPath()函数来获取用户选择的文件路径和名称。 文件对话框还可以设置过滤器来限制用户选择的文件类型。通过在构造wxFileDialog对象时设置wildcard参数,我们可以限定用户只能选择具有特定扩展名的文件。例如,通常我们可以设置过滤器为"Text Files (*.txt)|*.txt",这样在文件对话框中只能显示和选择.txt文件。 需要注意的是,wxFileDialog类是wxWidgets库中的一个封装类,它会根据不同的操作系统自动选择并使用相应的文件对话框。因此,使用wxFileDialog能够保证在不同的平台上都能正常工作。 总之,wxWidgets提供的文件对话框类(wxFileDialog)方便了开发人员与用户进行文件操作的交互。通过使用文件对话框,我们可以方便地打开、保存和选择文件路径和文件名,同时可以设置过滤器来限制用户的选择范围。这极大地简化了开发过程,并使得应用程序能够在不同的操作系统上保持一致的用户界面和体验。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值