Java Swing JFileChooser和JColorChooser:文件选择器和颜色选择器

  • 内容
  • 评论
  • 相关

在开发应用程序时经常需要选择文件和选择颜色的功能。例如,从选择的文件中导入数据,为窗体选择背景颜色等。本节详细介绍 Swing 中文件选择器和颜色选择器的使用。

文件选择器

文件选择器为用户能够操作系统文件提供了桥梁。swing 中使用 JFileChooser 类实现文件选择器,该类常用的构造方法如下。

  • JFileChooser():创建一个指向用户默认目录的 JFileChooser。
  • JFileChooser(File currentDirectory):使用指定 File 作为路径来创建 JFileChooser。
  • JFileChooser(String currentDirectoryPath):创建一个使用指定路径的 JFileChooser。
  • JFileChooser(String currentDirectoryPath, FileSystemView fsv):使用指定的当前目录路径和 FileSystem View 构造一个 JFileChooser。

JFileChooser 类的常用方法如下所示。

  • int showOpenDialog(Component parent):弹出打开文件对话框。
  • int showSaveDialog(Component parent):弹出保存文件对话框。

例 1

编写一个程序允许用户从本地磁盘中选择一个文件,并将选中的文件显示到界面。实现代码如下:

package ch18;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class JFileChooserDemo
{
    private JLabel label=new JLabel("所选文件路径:");
    private JTextField jtf=new JTextField(25);
    private JButton button=new JButton("浏览");
    public JFileChooserDemo()
    {
        JFrame jf=new JFrame("文件选择器");
        JPanel panel=new JPanel();
        panel.add(label);
        panel.add(jtf);
        panel.add(button);
        jf.add(panel);
        jf.pack();    //自动调整大小
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        button.addActionListener(new MyActionListener());    //监听按钮事件
    }
    //Action事件处理
    class MyActionListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent arg0)
        {
            JFileChooser fc=new JFileChooser("F:\\");
            int val=fc.showOpenDialog(null);    //文件打开对话框
            if(val==fc.APPROVE_OPTION)
            {
                //正常选择文件
                jtf.setText(fc.getSelectedFile().toString());
            }
            else
            {
                //未正常选择文件,如选择取消按钮
                jtf.setText("未选择文件");
            }
        }
    }
    public static void main(String[] args)
    {
        new JFileChooserDemo();
    }
}

在上述程序中使用内部类的形式创建了一个名称为 MyActionListener 的类,该类实现了 ActionListener 接口。其中 showOpenDialog() 方法将返回一个整数,可能取值情况有 3 种:JFileChooser.CANCEL—OPTION、JFileChooser.APPROVE_OPTION 和 JFileChooser.ERROR_OPTION,分别用于表示单击“取消”按钮退出对话框,无文件选取、正常选取文件和发生错误或者对话框已被解除而退出对话框。因此在文本选择器交互结束后,应进行判断是否从对话框中选择了文件,然后根据返回值情况进行处理。

运行程序,单击“浏览”按钮,会弹出选择文件的对话框,如果取消选择,此时会显示未选择文件;否则就会显示选择的文件路径及文件名称,如图 1 所示。

 

本文标题:Java Swing JFileChooser和JColorChooser:文件选择器和颜色选择器

本文地址:https://www.hosteonscn.com/3608.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注