落后_追 2017-06-25 06:39 采纳率: 100%
浏览 1088
已结题

java 从JTextFiled中读取路径,打开文本

图片说明
就是向图片那样直接从JTextField中读取文件名字或者路径,点击按钮就能打开文本的事件。。。

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.BorderLayout;
import java.awt.FileDialog;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JScrollPane;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class OpenTxt extends JFrame{
public OpenTxt(){
super("打开文本文件");

this.setLayout(new BorderLayout());
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JButton b=new JButton("打开文本文件");
JLabel l=new JLabel("文本文件名称,位置:");
JTextField txt=new JTextField(20);
JTextArea txtContent =new JTextArea(20,10);
JScrollPane sp=new JScrollPane(txtContent);
p1.add(l);
p1.add(txt);
this.add(p1,BorderLayout.NORTH);
this.add(txtContent, BorderLayout.CENTER);

p2.add(b);
this.add(p2, BorderLayout.SOUTH);
this.setSize(500,600);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
         String FileName=txt.getText();
         File file=new File(FileName);
         String path=file.getAbsolutePath();

         try {
            BufferedReader br=new BufferedReader(new FileReader(path));
            String result=null;
            while((result=br.readLine())!=null){
                txtContent.append(result);
            }
        } catch (FileNotFoundException  e1) {
            e1.printStackTrace();
        }catch(IOException e1){
            e1.printStackTrace();
        }
    }
});


}


public static void main(String args[]){
    new OpenTxt();
}

}

我这种写法只能读取路径,不能直接读取名字~!
求大神指教~~!
谢谢

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
    • ¥15 vue3+express部署到nginx
    • ¥20 搭建pt1000三线制高精度测温电路
    • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
    • ¥15 画两个图 python或R
    • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
    • ¥15 八路抢答器设计出现故障
    • ¥15 opencv 无法读取视频
    • ¥15 按键修改电子时钟,C51单片机
    • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))