简体   繁体   中英

How to write text file using applet in java?

I am trying to create an applet that responses to a mouse click and then draws square on the screen and stores the mouse co-ordinates in string.Finally if I press 'S' key then it saves the string in a file named "Level1.txt". But when I am running this applet and pressing S nothing gets saved in file.I don't the reason.Please help. Here is my code:-

 import java.io.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
public class levelEditor extends Applet{
int x,y;
boolean clicked;
FileWriter fw;
PrintWriter pw;
BufferedWriter bw;
String pix;
    public void init() {
        setSize(500,500);
        x=0;
        y=0;
        pix="";

        clicked=false;
        addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent e){
                clicked=true;
                x=e.getX();
                y=e.getY();
                pix=pix+x+","+y+" ";
                repaint();
            }
        } );
        addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent e){
                try{
                    if(e.getKeyCode()==KeyEvent.VK_S){
                        fw=new FileWriter("Level1.txt");
                        bw=new BufferedWriter(fw);
                        pw=new PrintWriter(bw);
                        pw.println(pix);
                        pw.close();
                        System.exit(0);
                    }
                    }
                    catch(Exception exp)
                    {

                    }
            }
        });

    }
    public void paint(Graphics g){
        update(g);
    }
public void update(Graphics g){
    if(clicked){
    g.setColor(Color.GREEN);
    g.fillRect(x-5, y-5,10,10);

    }
}
}

You need a signed applet to access the local file system. See the Oracle docs: What Applets Can and Cannot do .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM