-1

Here is my code. I am trying to make a basic text editor just to try out file writing and reading along with JPanels and such. My current issue is that users are required to input the full file path of the file and that can get quite frustrating. So I made a button that allows the user to have preset file path settings. When you click on the 'File Path Settings' button, there is a window that pops up allowing you to set the settings. (A file browsing button will be implemented later I just wanted to do this for fun first.)

public class EventListeners {

    String textAreaValue;
    String filePath;
    String rememberedPath;
    String rememberedPathDirectory;
    //Global components
    JTextField fileName,saveFilePath,filePathSaveDirectory,savedFilePath;
    JButton save,help,savePath;
    //JTextArea text;

    public EventListeners(){
        window();
    }

    public void window(){
        JFrame window = new JFrame();
        window.setVisible(true);
        window.setSize(650,500); 
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        JButton saveFilePath = new JButton("File Path Save Settings");
        JTextArea ltext = new JTextArea(10,50);
        JLabel filler = new JLabel("                                ");
        JLabel lfileName = new JLabel("File Path(If error click help)");
        JLabel lsaveFilePath = new JLabel("Save Path");
        fileName = new JTextField(30);
        save = new JButton("Save File");
        help = new JButton("Help");

        panel.add(lfileName);
        panel.add(fileName);
        panel.add(save);
        panel.add(help);
        panel.add(ltext);
        panel.add(filler);
        window.add(panel);

        saveFilePath.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){
                //JOptionPane.showMessageDialog(null,"Hello world!");

                JFrame windowB = new JFrame();
                int windows = 2;
                windowB.setVisible(true);
                windowB.setSize(500,500); 
                windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JPanel panelB = new JPanel();
                JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
                filePathSaveDirectory = new JTextField(20);
                JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
                savedFilePath = new JTextField(20);
                savePath = new JButton("Save Settings");
                panelB.add(lFilePathSaveDirectory);
                panelB.add(filePathSaveDirectory);
                panelB.add(lsavedFilePath);
                panelB.add(savedFilePath);
                panelB.add(savePath);
                windowB.add(panelB);
            }
        });
        save.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textAreaValue = ltext.getText();
                filePath = fileName.getText();
                try {
                    FileWriter fw = new FileWriter(filePath);
                    PrintWriter pw = new PrintWriter(fw);

                    pw.println(textAreaValue);
                    pw.close();
                    JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
                } catch(IOException x) {
                    JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
                }
            }
        });
        help.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(panel, "       ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help",JOptionPane.PLAIN_MESSAGE);
            }
        });

        panel.add(saveFilePath);
        window.add(panel);
        saveFilePath.setSize(20,100); 

        savePath.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                rememberedPathDirectory = filePathSaveDirectory.getText();
                rememberedPath = savedFilePath.getText();
                try {
                    FileWriter fw = new FileWriter(rememberedPathDirectory+"filePathSettings.txt");
                    PrintWriter pw = new PrintWriter(fw);

                    pw.println(rememberedPath);
                    pw.close();
                    JOptionPane.showMessageDialog(panel, "File Written!","Success!",JOptionPane.PLAIN_MESSAGE);
                } catch(IOException x) {
                    JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers","Error",JOptionPane.ERROR_MESSAGE);
                }
                JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert",JOptionPane.WARNING_MESSAGE);
            }
        });
    }

    public static void main(String[] args) {
        new EventListeners();  
    }   
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
  • 1
    possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – sstan Aug 21 '15 at 16:57

2 Answers2

1

main problem is you are creating variable with same name inside the constructer, you already define as instance .then your instance variable keep uninitialized/null.

for example you have declare instance variable

JButton save, help, savePath, saveFilePath;

inside constructor you are creating another local jbutton and initialize it so instance variable is null. so instead of creating new one you should initialize instance field.

JButton saveFilePath = new JButton("File Path Save Settings"); // problem

saveFilePath = new JButton("File Path Save Settings"); // correct way

but there is a another problem ..you have declare saveFilePath instance field as a jtextfield and you have created a saveFilePath button inside the constructor .i think it may be a button not a textfield.

also you are initializing some variables inside saveFilePath.addActionListener(new ActionListener() { method but you are adding actionlistners to them before saveFilePath action fired .you have to add actionlistners after you initialized a component.

also you should call repaint() at last after you add all the component to a frame..

try to run this code

import javax.swing.*;
import java.awt.event.*;

import java.io.FileWriter;

import java.io.IOException;

import java.io.PrintWriter;

public class EventListeners {

    String textAreaValue;
    String filePath;
    String rememberedPath;
    String rememberedPathDirectory;
    //Global components
    JTextField fileName, filePathSaveDirectory, savedFilePath;
    JButton save, help, savePath, saveFilePath;
    //JTextArea text;

    public EventListeners() {
        window();
    }

    public void window() {

        JFrame window = new JFrame();

        window.setSize(650, 500);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel();
        saveFilePath = new JButton("File Path Save Settings");
        JTextArea ltext = new JTextArea(10, 50);
        JLabel filler = new JLabel("                                ");
        JLabel lfileName = new JLabel("File Path(If error click help)");
        JLabel lsaveFilePath = new JLabel("Save Path");
        fileName = new JTextField(30);
        save = new JButton("Save File");
        help = new JButton("Help");

        panel.add(lfileName);
        panel.add(fileName);
        panel.add(save);
        panel.add(help);
        panel.add(ltext);
        panel.add(filler);
        window.add(panel);

        saveFilePath.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                //JOptionPane.showMessageDialog(null,"Hello world!");

                JFrame windowB = new JFrame();
                int windows = 2;
                windowB.setVisible(true);
                windowB.setSize(500, 500);
                windowB.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                JPanel panelB = new JPanel();
                JLabel lFilePathSaveDirectory = new JLabel("Directory where the file path settings will be stored");
                filePathSaveDirectory = new JTextField(20);
                JLabel lsavedFilePath = new JLabel("The full file path or part you want stored.");
                savedFilePath = new JTextField(20);
                savePath = new JButton("Save Settings");
                panelB.add(lFilePathSaveDirectory);
                panelB.add(filePathSaveDirectory);
                panelB.add(lsavedFilePath);
                panelB.add(savedFilePath);
                panelB.add(savePath);
                windowB.add(panelB);
                System.out.println(savePath);
                savePath.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                        rememberedPathDirectory = filePathSaveDirectory.getText();
                        rememberedPath = savedFilePath.getText();
                        try {
                            FileWriter fw = new FileWriter(rememberedPathDirectory + "filePathSettings.txt");
                            PrintWriter pw = new PrintWriter(fw);

                            pw.println(rememberedPath);
                            pw.close();
                            JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
                        } catch (IOException x) {
                            JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
                        }
                        JOptionPane.showMessageDialog(panel, "The application will close. Anythings not saved will be deleted", "Alert", JOptionPane.WARNING_MESSAGE);
                    }
                });

            }

        });
        save.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textAreaValue = ltext.getText();
                filePath = fileName.getText();
                try {
                    FileWriter fw = new FileWriter(filePath);
                    PrintWriter pw = new PrintWriter(fw);

                    pw.println(textAreaValue);
                    pw.close();
                    JOptionPane.showMessageDialog(panel, "File Written!", "Success!", JOptionPane.PLAIN_MESSAGE);
                } catch (IOException x) {
                    JOptionPane.showMessageDialog(panel, "Error in writing file. \n\n Try Checking the file path or making sure the directory in which you are saving the file exists. \n\n Keep Calm and Love Beavers", "Error", JOptionPane.ERROR_MESSAGE);
                }

            }
        });
        help.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(panel, "       ***The file name must be the full file path.***\n\n-=-=-=-=-=-=-=-=-=(MAC)=-=-=-=-=-=-=-=-=-\n\n Example: /Users/Cheese/Documents/FileName.txt\n\n\n-=-=-=-=-=-=-=-=(WINDOWS)=-=-=-=-=-=-=-=-\n\n *Note that 2 back slashes must be used* \n\nC:\\user\\docs\\example.txt", "Help", JOptionPane.PLAIN_MESSAGE);
            }
        });

        panel.add(saveFilePath);
        window.add(panel);
        saveFilePath.setSize(20, 100);
        window.setVisible(true);
    }

    public static void main(String[] args) {

        new EventListeners();

    }

}
Madhawa Priyashantha
  • 9,633
  • 7
  • 33
  • 60
  • Now, this revision throws no error when there should be one when writing a file. it will always say "File Written". Thank you for all your help but i need just a little more – The Buggiest of Code Aug 21 '15 at 17:38
  • @TheBuggiestofCode you need to check ..anyway for me it's working if you click save without entering path a error will display, – Madhawa Priyashantha Aug 21 '15 at 17:50
0

You also may want to consider dependency injection. That is becoming the standard way of doing things in the industry. Instead of the constructor doing all the work of creating all the objects your class uses, or calling another method like window() to do all the work, you pass in all the specifications to the constructor. It might look something like

public EventListeners(JButton save, JButton help, JButton saveFilePath) {
    this.save = save;
    this.help = help;
    this.saveFilePath = saveFilePath);
}

Of course, you could also use a dependency injection framework like Spring, but that might be a bit much if your application is small.

Paul J Abernathy
  • 993
  • 2
  • 12
  • 25