How to insert text in a text file by using GUI
To insert text in a text file you will need
a FileWriter from the java bibliotheca. In this case I use a graphical
interface to put text in a document. For
button use you´ll need an ActionListener. This ActionListener also run the
function FileWriter.
1. 1. Create an GUI
import
java.awt.BorderLayout;
import
java.awt.Button;
import
java.awt.Color;
import
java.awt.Dimension;
import
java.awt.FlowLayout;
import
java.awt.GridLayout;
import
java.awt.Label;
import
java.awt.Panel;
import
java.awt.TextField;
import
java.awt.event.ActionListener;
import
javax.swing.JFrame;
public
class Eingabe extends Panel{
static Eingabe ein;
static TextField txt;
public
Eingabe (){
setLayout (new BorderLayout());
setPreferredSize(new
Dimension(200,50));
Panel p1 = new Panel();
p1.setLayout(new
FlowLayout(100,20,10));
txt = new TextField();
txt.setPreferredSize(new
Dimension(100, 20));
Button b1 = new Button
("OK");
b1.setPreferredSize(new
Dimension(50,20));
b1.setForeground(Color.BLUE);
ActionListener
ActionListener1 = new ActionListener1 ();
b1.addActionListener(ActionListener1);
p1.add(b1);
p1.add(txt);
add(p1,
BorderLayout.CENTER);
}
public
static void main (String[]args){
ein = new Eingabe();
JFrame
f = new JFrame("Eingabe");
f.add(ein,
BorderLayout.SOUTH);
f.pack();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
}
|
|
Now you´ll have your Window:
For saving a text you need an
ActionListener and the function FileWriter.
1. 2. Create an
ActionListener Class; first for the button action and second for the FileWriter
action
import
java.awt.event.ActionEvent;
import
java.awt.event.ActionListener;
import java.io.File;
import
java.io.FileWriter;
import
java.io.IOException;
public class
ActionListener1 implements ActionListener{
public void
actionPerformed(ActionEvent event){
String
tx = Eingabe.txt.getText(); //set a parameter for getting the textfield
FileWriter
ef;
File
f;
f
= new File("Eingabe.txt"); //function for FileWriter
try{
ef=
new FileWriter(f,true);
ef.write(tx);
//write the text in an document
ef.flush();
ef.close();
}
catch(IOException
e){
e.printStackTrace();
}
}
}
|
Now type in a text…
…and press the button…
…it creates a text document…