如何在Jframe中使用java文件选择器? [英] How to use java file chooser in Jframe?

查看:445
本文介绍了如何在Jframe中使用java文件选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用jframe中的文件选择器时遇到问题。我想使用文件选择器在特定位置保存文件并从特定位置打开文件。

I am facing a problem using a file chooser in a jframe. I want to save a file in a specific place using file chooser and open a file from the specific place.

推荐答案

尝试使用此代码进行关闭,打开,保存按钮:



Try using this code for your close, open, save buttons:

public void actionPerformed(ActionEvent e) {

		if(e.getSource()==close){
			this.dispose();
		}
		
		if(e.getSource()==open){
			
			JFileChooser choose=new JFileChooser();  //create a new JFileChooser instance
		
			int option=choose.showOpenDialog(this);
			if(option==JFileChooser.APPROVE_OPTION){  // ok button in dialog chose frame
				
				this.textArea.setText(" ");
				try {
					
					Scanner scan=new Scanner(new FileReader(choose.getSelectedFile().getPath()));  
				
   //you need a scanner to read lines in your text file, a stream FileReader to read the text file
					while(scan.hasNext()){
						textArea.append(scan.nextLine()+"\n");
					}
					
				} catch (FileNotFoundException e1) {
					e1.printStackTrace();
				}
				
			}
			
		}// open getSource()
		
		if(e.getSource()==save){
			
			JFileChooser save=new JFileChooser();
			int option=save.showSaveDialog(this);
			
			if(option==JFileChooser.APPROVE_OPTION){
				
				try {
					BufferedWriter bw=new BufferedWriter(new FileWriter(save.getSelectedFile().getPath()));  //a bufferedwriter( a high level stream writer )
					bw.write(textArea.getText());
					bw.close();
					
				} catch (IOException e1) {
					e1.printStackTrace();
				}
			}
			
		}
		
	}


请查看示例此处。请参阅此链接



干杯,

Sudhakar
Please find an example here. Refer to this link as well.

Cheers,
Sudhakar


这篇关于如何在Jframe中使用java文件选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆