I want to make a user/pass an a checkButton to keep the user and pass. So, first time when I open the app and put the pass and user and select the rememberBox to save this check and after I will open again to remain check and the pass and user to be written already.
This is the code:
JButton btnLogin = new JButton("Login");
Image ok = new ImageIcon(this.getClass().getResource("/Ok.png")).getImage();
btnLogin.setIcon(new ImageIcon(ok));
btnLogin.addActionListener(new ActionListener() {
#SuppressWarnings("deprecation")
public void actionPerformed(ActionEvent arg0) {
String user = "marius";
String password = "Amina1";
UPDATE();
if(userName.getText().equals(user) && passwordField.getText().equals(password)){
if(checkBox.isSelected()){
SAVE(); //Save This UserName and his PassWord
}
window.frmUserpass.dispose();
WelcomePage welcomePage = new WelcomePage();
welcomePage.Screen1();
}else {
JOptionPane.showMessageDialog(btnLogin, "Introduceti unuser si o parola valida!", "Error", 0);
passwordField.selectAll();
}
}
private void SAVE() {
try {
if(!file.exists()) file.createNewFile(); //if the file !exist create a new one
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsolutePath()));
bw.write(userName.getText()); //write the name
bw.newLine(); //leave a new Line
bw.write(passwordField.getPassword()); //write the password
bw.close(); //close the BufferdWriter
} catch (IOException e) { e.printStackTrace(); }
}
private void UPDATE() {
try {
if(file.exists()){ //if this file exists
Scanner scan = new Scanner(file); //Use Scanner to read the File
userName.setText(scan.nextLine()); //append the text to name field
passwordField.setText(scan.nextLine()); //append the text to password field
scan.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
});
btnLogin.setBounds(231, 112, 89, 23);
frmUserpass.getContentPane().add(btnLogin);
Related
I need hlep with figuring out how to wrap the text in the JavaFX TextField object.
So my code gets a file name from the user, opens the file by pasting the contents of the text file into the text field. Then the user can edit the text and save it into the same file.
My code does all of the above so that's not what I need help with. The JavaFX TextField object does not seem to have a way to wrap the text in the text box. It ends up looking like this:
Alt Image Link: https://drive.google.com/open?id=1q2yU5ox6WA5EwS3YSxaKoqUDpCxpbPmu
I want to wrap the text for obvious reasons. Below is my code (minus the import statements)
public class TextEditor extends Application
{
private Button button = new Button();
private TextField text = new TextField();
private Label label = new Label("Enter filename:");
private String filename = "";
String filetext = "";
Scanner file = new Scanner("");
PrintWriter pw = null;
FileOutputStream fos = null;
#Override
public void start(Stage primaryStage) throws Exception
{
GridPane myPane = new GridPane();
myPane.setHgap(10);
myPane.setVgap(10);
Scene myScene = new Scene(myPane, 500, 500);
primaryStage.setScene(myScene);
primaryStage.show();
primaryStage.setTitle("Find File");
myPane.setAlignment(Pos.BASELINE_CENTER);
label.setAlignment(Pos.BASELINE_CENTER);
myPane.add(label, 0, 0, 3, 1);
text.setAlignment(Pos.TOP_LEFT);
text.setPrefWidth(480);
text.setPrefHeight(400);
myPane.add(text, 0, 1);
button = new Button("Submit Filename");
button.setPrefSize(180, 50);
button.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
if(button.getText().equals("Save Changes"))
{
try
{
fos = new FileOutputStream(filename);
pw = new PrintWriter(fos);
System.out.println("Saving changes in " + filename);
pw.println(text.getText());
pw.close();
primaryStage.close();
}
catch (FileNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
if(button.getText().equals("Submit Filename"))
{
filename = text.getText();
try
{
file = new Scanner(new FileInputStream(new File(filename)));
while(file.hasNextLine())
{
String line = file.nextLine();
System.out.println(line);
filetext += line + "\n";
}
System.out.println("File text: " + filetext);
text.setText(filetext);
button.setText("Save Changes");
}
catch(FileNotFoundException exc)
{
System.out.println("Cannot find file. Program aborted.");
primaryStage.close();
}
}
}
});
myPane.add(button, 0, 2);
}
public static void main(String[] args)
{
Application.launch(args);
}
}
Would love some assistance getting the text to wrap. Do I need to not use a JavaFX TextField? Should I use something else?
Thanks in advance!
EDIT
SOLUTION FOUND
I changed the TextField text to a TextArea, removed the text.setAlignment(Pos.TOP_LEFT) line and added a text.setWrapText(true) (as suggested below) and now the program works great. Thanks Fabian and Zephyr!
I have a small GUI project with a text-box and submit button. What I want to do is for user to type into the text-box and submit an input that would move them through the program (ex. 1 to go to next menu). The program did not use to have a GUI and used console to enter input (as seen in the first code) and so I want to move the program away from console.
Right now my main is:
public static void main(String[] args) {
//Initialize menu variable
Menu menu = MainMenu.getInstance();
new Console();
while (true){
//Display current menu
menu.displayMenu();
while (menu.moreInputNeeded()){
menu.displayPrompt();
try {
// Process user input.
menu.parseInput(new BufferedReader(new InputStreamReader(System.in)).readLine());
} catch (IOException e) {
// printStackTrace();
System.out.println(Prompt.INVALID_INPUT);
}
}
menu = menu.getNextMenu();
}
}
and I use a text/submit button as followed:
//Create the Text Box
JTextField textField = new JTextField(20);
//Submit Button
JButton submit = new JButton("Submit");
//Submit Function
submit.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
menuinput = textField.getText();
textField.setText("");
//
System.out.println(menuinput);
}
});
So is it possible to process user input from the GUI instead of the console?
I was able to figure out my own question. I implemented:
//Variables
JTextField tfIn;
JLabel lblOut;
private final PipedInputStream inPipe = new PipedInputStream();
private final PipedInputStream outPipe = new PipedInputStream();
PrintWriter inWriter;
String input = null;
Scanner inputReader = new Scanner(System.in);
//Variables
System.setIn(inPipe);
try {
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
inWriter = new PrintWriter(new PipedOutputStream(inPipe), true);
}
catch(IOException e) {
System.out.println("Error: " + e);
return;
}
tfIn = new JTextField();
tfIn.addActionListener(this);
frame.add(tfIn, BorderLayout.SOUTH);
With Method:
public synchronized void actionPerformed(ActionEvent evt)
{
textArea.setText("");
String text = tfIn.getText();
tfIn.setText("");
inWriter.println(text);
}
There might be some other little aspects I missed but that's the most important parts.
So I started create this project for my PAT Grade 12 task and I hit a speedbump...
I have a login screen, using a jFrame, in netbeans.
My issue is, that I am using 2 text files to store the data: 1 for usernames and 1 for passwords. They are read in using a Scanner and are being delimited with a #.
The point is, I validate the Username using a while loop, but i am unable to validate the password that correspond with that username in the other text file.
So you can imagine 2 text files:
Username
Password
When the 'Login' button is clicked, it uses a while loop to check to see if username already exists. If it does, continue to the Password, else "Username does not exist". The problem comes in when matching the Password, in the same position, in the other text file.
If anybody can help me, it would make my week and save my project.
Please understand that Netbeans only lets you edit certain areas of code. I try my best to keep my code clean and understandable.
Many Thanks,
SnowyTheVampire
package Battlefield4;
import javax.swing.*;
import java.util.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Login extends javax.swing.JFrame
{
String Username;
String Password;
public Login()
{
initComponents();
}
//Can not edit from here on
private void initComponents() {
txtUsername = new javax.swing.JTextField();
txtPassword = new javax.swing.JTextField();
lblPassword = new javax.swing.JLabel();
lblUsername = new javax.swing.JLabel();
btnLogin = new javax.swing.JButton();
btnCreate = new javax.swing.JButton();
jLabel1 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setSize(new java.awt.Dimension(854, 480));
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
getContentPane().add(txtUsername, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 150, 210, -1));
getContentPane().add(txtPassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 220, 210, -1));
lblPassword.setText("Password");
getContentPane().add(lblPassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 200, -1, -1));
lblUsername.setText("Username");
getContentPane().add(lblUsername, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 130, -1, -1));
btnLogin.setText("Login");
btnLogin.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnLoginActionPerformed(evt);
}
});
getContentPane().add(btnLogin, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 290, -1, -1));
btnCreate.setText("Create");
btnCreate.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCreateActionPerformed(evt);
}
});
getContentPane().add(btnCreate, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 290, -1, -1));
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Battlefield4/Batfield/Background/Login (Small).jpg"))); // NOI18N
jLabel1.setText("jLabel1");
getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 860, 480));
pack();
}
//Can not edit before this
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
//This is from where Netbeans lets you edit your code.
try {
File user = new File("C:\\Users\\John1012\\Documents\\NetBeansProjects\\PATProject\\src\\Battlefield4\\Batfield\\Users\\Username.txt"); //To create a universal file for Input & Output
File pass = new File("C:\\Users\\John1012\\Documents\\NetBeansProjects\\PATProject\\src\\Battlefield4\\Batfield\\Users\\Password.txt"); //To create a universal file for Input & Output
user.getParentFile().mkdirs(); //To denote the parent file
pass.getParentFile().mkdirs(); //To denote the parent file
Scanner scUser = new Scanner(user).useDelimiter("#"); //To scan the Username file
Scanner scPass = new Scanner(pass).useDelimiter("#");
Username = txtUsername.getText(); //This gets the user input
Password = txtPassword.getText(); //This gets the user input
int pos = 0; //Indicates the position of the Username in the save file
while(scUser.hasNext())
{
pos = pos + 1;
if(scUser.equals(Username))
{ //This is where it fails
for (int i = 0; i <= 5; i++)
{
while(scPass.hasNext())
{
System.out.print(scPass);
}
}
if(scPass.equals(Password))
{
new Selection().setVisible(true);
this.dispose();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password!");
}
}//This is where it works from. The above code is sketchy
else
{
JOptionPane.showMessageDialog(null,"User Does Not Exist!");
}
scUser.close();
}
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {
//Again this is from where Netbeans lets you edit
try {
File user = new File("C:\\Users\\John1012\\Documents\\NetBeansProjects\\PATProject\\src\\Battlefield4\\Batfield\\Users\\Username.txt"); //To create a universal file for Input & Output
File pass = new File("C:\\Users\\John1012\\Documents\\NetBeansProjects\\PATProject\\src\\Battlefield4\\Batfield\\Users\\Password.txt"); //To create a universal file for Input & Output
user.getParentFile().mkdirs(); //To denote the parent file
pass.getParentFile().mkdirs(); //To denote the parent file
Scanner scUser = new Scanner(user); //To scan the Username file
Username = txtUsername.getText(); //This gets the user input
Password = txtPassword.getText(); //This gets the user input
if(scUser.nextLine().contains(Username)) //This reads the entire line and checks for an indexOf of those characters
{
JOptionPane.showMessageDialog(null,"User Already Exists!");
scUser.close(); //Close the Scanner
}
else
{
scUser.close(); //Close the Scanner
if("".equals(Password) || " ".equals(Password)) //Checks to see whether or not the user entered a password
{
JOptionPane.showMessageDialog(null,"Please Enter A Password!");
}
else
{
PrintWriter pwUser = new PrintWriter(new FileWriter(user,true)); //To Write to the Username file
PrintWriter pwPass = new PrintWriter(new FileWriter(pass,true)); //To Write to the Password file
pwUser.print(Username + "#");
pwPass.print(Password + "#");
pwUser.close();
pwPass.close();
new Selection().setVisible(true);
this.dispose();
}
}
scUser.close();
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
//Can no longer edit here
public static void main(String args[]) {
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Login().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JButton btnCreate;
private javax.swing.JButton btnLogin;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel lblPassword;
private javax.swing.JLabel lblUsername;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtUsername;
// End of variables declaration
}
Map all users on startup and then just check the map. Use split to separate the username and password. Check that the inputs are not empty before calling onLoginCorrect()
private static final Logger LOG = LogManager.getLogger();
private final Map<String, String> users = new ConcurrentHashMap<>();
public Login() {
super();
final InputStream resource = this.getClass().getResourceAsStream("/users.txt");
final Scanner scanner = new Scanner(resource);
while (scanner.hasNext()) {
final String input = scanner.nextLine();
final String[] userPw = StringUtils.split(input, ':');
this.users.put(userPw[0], userPw[1]);
}
scanner.close();
IOUtils.closeQuietly(resource);
}
public boolean isLoginCorrect(final String username,final String password) {
final boolean result;
if (StringUtils.equals(this.users.get(username), password)) {
result = true;
} else {
Login.LOG.warn("No such user");
result = false;
}
return result;
}
So I figured out how to do it. Thanks everyone for the help!
I am posting this as a simpler method to #Tobi in hopes to help people that aren't as advanced or need simpler help!
private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
try {
File user = new File("src\\Battlefield4\\Batfield\\Users\\Username.txt"); //To create a universal file for Input & Output
File pass = new File("src\\Battlefield4\\Batfield\\Users\\Password.txt"); //To create a universal file for Input & Output
user.getParentFile().mkdirs(); //To denote the parent file
pass.getParentFile().mkdirs(); //To denote the parent file
Scanner scUser = new Scanner(user).useDelimiter("#"); //To scan the Username file
Scanner scPass = new Scanner(pass).useDelimiter("#"); //To scan the password file
username = txtUsername.getText(); //This gets the user input
password = txtPassword.getText(); //This gets the user input
int pos = 0; //Indicates the position of the Username in the save file
boolean loggedIn = false; //Flag to check if it's logged in
while(scUser.hasNext() && scPass.hasNext()) //Runs files in congruency
{
if(scUser.next().equalsIgnoreCase(username) && scPass.next().equals(password))
{
loggedIn = true;
scUser.close();
scPass.close();
new Selection(username).setVisible(true);
this.dispose();
break;
}
}
scUser.close();
scPass.close();
if(loggedIn == false)
{
JOptionPane.showMessageDialog(null,"Incorrect Username or Password!");
}
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
}
I have a program which asks you for your first name and second name. I used OutputStream to save the first name in a file stored in the workspace. I use a BufferedReader to read the file but I'm trying to get it so if the person clicks yes on the JOptionPane.YES_NO_DIALOG, it uses the name in the file! I've tried doing and if Statement that said if JOptionPane... then text.setText(savedName), but it just comes out as "Welcome null null"
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class BingoHelper extends JFrame implements WindowListener, ActionListener{
JTextField text = new JTextField();
//JLabel bg = new JLabel("helo");
private JButton b; {
b = new JButton("Click to enter name");
}
JPanel pnlButton = new JPanel();
public static String fn;
public static String sn;
public static int n;
File f = new File("test.txt");
public void actionPerformed (ActionEvent e){
Object[] yesNo = {"Yes",
"No",};
n = JOptionPane.showOptionDialog(null,"Would you like to use previously entered data?","Welcome Back?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, yesNo,yesNo[1]);
if (n == JOptionPane.NO_OPTION){
for(fn=JOptionPane.showInputDialog("What is your first name?");!fn.matches("[a-zA-Z]+");fn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
fn=JOptionPane.showInputDialog("What is your first name?");
}
for(sn=JOptionPane.showInputDialog("What is your second name?");!sn.matches("[a-zA-Z]+");sn.isEmpty()){
JOptionPane.showMessageDialog(null, "Alphabet characters only.");
sn=JOptionPane.showInputDialog("What is your second name?");
}
}
//JOptionPane.showMessageDialog(null, "Welcome " + fn + " " + sn + ".", "", JOptionPane.INFORMATION_MESSAGE);
text.setText("Welcome " + fn + " " + sn + ".");
b.setVisible(false);
b.setEnabled(false);
text.setVisible(true);
text.setBounds(140,0,220,20);
text.setHorizontalAlignment(JLabel.CENTER);
text.setEditable(false);
text.setBackground(Color.YELLOW);
pnlButton.setBackground(Color.DARK_GRAY);
writeToFile();
//bg.setVisible(true);
}
private void writeToFile() {
String nameToWrite = fn;
OutputStream outStream = null;
try {
outStream = new FileOutputStream(f);
outStream.write(nameToWrite.getBytes());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(f)));
String savedName = br.readLine();
//System.out.println(savedName);
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (null != outStream) {
try {
outStream.close();
} catch (IOException e) {
// do nothing
}
}
}
}
When you use JOptionPane with your own options JOptionPane will return the index of the option select by the user...
That is, in your case, if the user selects "Yes", then JOptionPane will return 0 or if the user selects "No", it will return 1
So, instead of using JOptionPane.NO_OPTION you need use 1, for example...
Object[] yesNo = {"Yes",
"No",};
n = JOptionPane.showOptionDialog(null,"Would you like to use previously entered data?","Welcome Back?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, yesNo,yesNo[1]);
if (n == 1){
//...
}
I would also, strongly, encourage you to avoid using static field references in this context as it may result in unexpected behaviour if you ever get more then one instance of the class running ;)
I am creating an editor in java. I would like to know how to save an intermediate state in java?
For Example when user wants to save the changes done on the editor, how could it be done and also should be reloaded later.
Eg. powerpoint application is saved as .ppt or .pptx. Later the same .ppt while could be opened for further editions. I hope I am clear with my requirement.
The Preferences API with user preferences; most recently edited files, per file maybe timestamp + cursor position, GUI settings.
To save the contents of JTextPane you can serialize the DefaultStyledDocument of JTextPane in a file using proper way of serialization. And when you want to load the content again you can deserialize the same and display it on the JTextPane . Consider the code given below:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SaveEditor extends JFrame implements ActionListener{
public static final String text = "As told by Wikipedia\n"
+"Java is a general-purpose, concurrent, class-based, object-oriented computer programming language."
+ "It is specifically designed to have as few implementation "
+ "dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), "
+ "meaning that code that runs on one platform does not need to be recompiled to run on another. "
+ "Java applications are typically compiled to bytecode (class file) that can run on any Java virtual "
+ "machine (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming "
+ "languages in use, particularly for client-server web applications, with a reported 10 million users.";
JTextPane pane ;
DefaultStyledDocument doc ;
StyleContext sc;
JButton save;
JButton load;
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
SaveEditor se = new SaveEditor();
se.createAndShowGUI();
}
});
} catch (Exception evt) {}
}
public void createAndShowGUI()
{
setTitle("TextPane");
sc = new StyleContext();
doc = new DefaultStyledDocument(sc);
pane = new JTextPane(doc);
save = new JButton("Save");
load = new JButton("Load");
JPanel panel = new JPanel();
panel.add(save);panel.add(load);
save.addActionListener(this);load.addActionListener(this);
final Style heading2Style = sc.addStyle("Heading2", null);
heading2Style.addAttribute(StyleConstants.Foreground, Color.red);
heading2Style.addAttribute(StyleConstants.FontSize, new Integer(16));
heading2Style.addAttribute(StyleConstants.FontFamily, "serif");
heading2Style.addAttribute(StyleConstants.Bold, new Boolean(true));
try
{
doc.insertString(0, text, null);
doc.setParagraphAttributes(0, 1, heading2Style, false);
} catch (Exception e)
{
System.out.println("Exception when constructing document: " + e);
System.exit(1);
}
getContentPane().add(new JScrollPane(pane));
getContentPane().add(panel,BorderLayout.SOUTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == save)
{
save();
}
else if (evt.getSource() == load)
{
load();
}
}
private void save()//Saving the contents .
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Save");
int returnVal = chooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file != null)
{
FileOutputStream fos = null;
ObjectOutputStream os = null;
try
{
fos = new FileOutputStream(file);
os = new ObjectOutputStream(fos);
os.writeObject(doc);
JOptionPane.showMessageDialog(this,"Saved successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (Exception ex){}
}
if (os != null)
{
try
{
os.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
private void load()//Loading the contents
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Open");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file!= null)
{
FileInputStream fin = null;
ObjectInputStream ins = null;
try
{
fin = new FileInputStream(file);
ins = new ObjectInputStream(fin);
doc = (DefaultStyledDocument)ins.readObject();
pane.setStyledDocument(doc);
JOptionPane.showMessageDialog(this,"Loaded successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fin != null)
{
try
{
fin.close();
}
catch (Exception ex){}
}
if (ins != null)
{
try
{
ins.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}