Thursday 13 August 2015

Filled Under: ,

How To Save Text File Using JFile Chooser And JText Area In Java

As we see in most popular text editors such as notepad or word that there is option of save file by using this option we can save our text file .This tutorial shows how to create a your own text editor that can save text written in our text editor files.To perform this task we need one text area to write a file which we want to save  and a file chooser to select location in which you want to save a file.

RELATED TUTORIALS:

CODING:

import javax.swing.*; 
import java.awt.*;
import java.awt.event.*;
import java.io.*;
class myjframe1 extends JFrame implements ActionListener
{
JTextArea textArea = new JTextArea();
JMenuBar menuBar = new JMenuBar();  
JMenu file = new JMenu();
JMenuItem open = new JMenuItem();


public myjframe1() 
{

setTitle("Saving Txt File");
setSize(300, 200);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);      
textArea = new JTextArea(20,40);
menuBar.add(file);
file.setText("File");
file.add(open);
setJMenuBar(menuBar);
open.setText("Save File");
setLayout(new FlowLayout(FlowLayout.CENTER));
JScrollPane js = new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); 
add(js);
open.addActionListener(this);
}
public void actionPerformed(ActionEvent e) 
{
if (e.getSource() == open)
{
JFileChooser save = new JFileChooser();
int option = save.showSaveDialog(this);
File file = new File(save.getSelectedFile().getPath());
try
{
String source = textArea.getText();
char buffer[] = new char[source.length()];
source.getChars(0,source.length(),buffer,0);

FileWriter f1= new FileWriter(file+".txt");
for(int i=0;i<buffer.length;i++)
{
f1.write(buffer[i]);
}
f1.close();

}
catch(Exception ae)
{}
}
}
}
class savingtext
{
public static void main(String args[]) 
{
myjframe1 x= new myjframe1();
}
}

OUTPUT:





0 comments:

Post a Comment