芥末好多不会 2016-05-13 15:56 采纳率: 0%
浏览 3754

如何使用swing/SWT,点一个按钮就能打开本地的一个文件?

想用eclipse做一个可视化界面,使点击一个按钮就能打开本地已经存在的文件

  • 写回答

1条回答 默认 最新

  • whl85420 2016-05-13 19:44
    关注

    import java.awt.*;
    import java.io.*;
    import java.awt.event.*;

    public class wenjian
    extends Frame
    implements ActionListener {
    FileDialog open = new FileDialog(this, "打开文件",
    FileDialog.LOAD);
    String fileName;
    Button b_dakai = new Button("打开");
    TextArea text = new TextArea();
    wenjian() {
    super("文件的打开");
    setBounds(400, 200, 400, 300);
    b_dakai.addActionListener(this);
    add(text);
    add(b_dakai, "South");
    setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
    if (e.getSource() == b_dakai) {
    open.show();
    fileName = open.getDirectory() + open.getFile();
    if (fileName != null) {
    readFile(fileName);
    }
    }
    }

    // 这是一个打开文件文件的方法
    public void readFile(String fileName) {
    try {
    File file = new File(fileName);
    FileReader readIn = new FileReader(file);
    int size = (int) file.length();
    int charsRead = 0;
    char[] content = new char[size];
    while (readIn.ready()) {
    charsRead += readIn.read(content, charsRead, size - charsRead);
    }
    readIn.close();
    text.setText(new String(content, 0, charsRead));
    }
    catch (IOException e) {
    System.out.println("Error Opening file");
    }
    }

    public static void main(String args[]) {
    new wenjian().addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    };
    });
    ;
    }
    }

    评论

报告相同问题?

悬赏问题

  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作