How to make a save button

1.7k views Asked by At

I am trying to make a save button but I don't know how to do it. I will explain a little bit about my program. When someone start the program it shows a JOptionPane and the user need to write a nickname and then when he clicks on OK button it saves his nickname in a text.file. This is a part from my code.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.*;
import javax.swing.event.*;



public class SummerExamProject extends JFrame  {
   JButton Exit, About, Question1, Question2, Question3, Question4;
   JPanel panel, panel2, panel3, panel4 ;

   public  SummerExamProject(){
        initUI();

    }

public void  initUI(){

    setTitle("Java");
    setSize(500, 450);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(EXIT_ON_CLOSE);


JFrame frame = new JFrame();
JFrame frame1 = new JFrame("");
JPanel panel = new JPanel();
JPanel panel2 = new JPanel();
getContentPane().add(panel);
panel.setLayout(new GridLayout(0,3,8,9));




String code = JOptionPane.showInputDialog(frame1, " Enter a nickname ", "Nickname needed", JOptionPane.WARNING_MESSAGE);
2

There are 2 answers

2
Kiki On BEST ANSWER

If you want to store nickname to file you can use PrintWriter. Lets say you saved the nickname in String variable called nickname:

String nickname = "myAwesomeNickname";

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("c:/nicknames.txt", true)));
    out.println(nickname);
    out.close();
} catch (IOException e) {
    //exception handling 
}
0
dly On
PrintStream out = null;
    try {
        out = new PrintStream(new FileOutputStream("text.txt"));
        out.print(code);  // your String here
    } catch (IOException e) {
    } finally {
        if (out != null)
            out.close();
    }

text.txt can also be a full path like new FileOutputStream("D:/folder/text.txt") There are a few more options to write to files, though.