JavaSE series code 60: Application of file dialog

The swing component is independent of the local window system. The swing component starts with J except for the abstractbutton class. The swing component is built on AWT. § contains alternative components for AWT visualization components, as well as complex components - trees and tables

import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class Javase_60 extends Frame implements ActionListener
{
  static Javase_60 frm=new Javase_60 ();
  static FileDialog ofd=new FileDialog(frm, "打开");  //创建文件对话框ofd
  static FileDialog sfd=new FileDialog(frm, "保存", FileDialog.SAVE);
  static TextArea ta=new TextArea(8,30);
  static Button fbt_open=new Button("选取");
  static Button fbt_save=new Button("存盘");
  public static void main(String[] args)
  {
    frm.setTitle("文件对话框的应用");
    frm.setSize(300,230);
    frm.setLayout(new FlowLayout(FlowLayout.CENTER,15,10));
    frm.add(ta);   frm.add(fbt_open);   frm.add(fbt_save);
    fbt_open.addActionListener(frm);      //设置窗口中按钮的监听者为frm
    fbt_save. addActionListener(frm);
    frm.setVisible(true);
  }
  public void actionPerformed(ActionEvent e)  //单击窗口中按钮时的处理操作
  {
    Button bt=(Button)e.getSource();     //获取被单击的按钮
    if (bt==fbt_open)                  //若单击的是窗口中的“选取”按钮
    {
      ofd.setVisible(true);              //显示文件打开对话框,并掌握主控权
      String fname=ofd.getDirectory()+ofd.getFile();   //获取路径与文件名
      try
      {
        FileInputStream fi=new FileInputStream(fname);  //创建输入流
        byte[] fc=new byte[fi.available()];  //以文件长度为大小定义数组
        fi.read(fc);      //将读取的内容写入到数组fc中
        ta.setText(new String(fc));   //将数组fc中的内容显示在文本区ta内
        fi.close();
      }
      catch(IOException ioe){};
    }
    else if(bt==fbt_save)        //若单击的是窗口中的“存盘”按钮
    {
      sfd.setVisible(true);       //显示文件保存对话框,并掌握主控权
      String fname=sfd.getDirectory()+sfd.getFile();    //获取路径与文件名
       try {
        FileOutputStream fs=new FileOutputStream(fname);  //创建输出流
        fs.write(ta.getText().getBytes());   //将ta中的内容转换成字节后写入文件fs中
        fs.close(); 
      } catch(IOException ioe){};
    }
  }
}
Published 73 original articles · praised 189 · 10,000+ views

Guess you like

Origin blog.csdn.net/blog_programb/article/details/105566570