简体   繁体   中英

Java Swing text editor throws NullPointerException

Alright... I'm starting out with Java and I've stepped up to Swing GUI. Everything was going fine until I tried to work with file input and output.

    /*
    ** 'Gooey' GUI in Swing with Java.
    ** v3 With File Opening
    */

    import javax.swing.*; // Import the swing library
    import javax.swing.filechooser.*;
    import java.awt.*; // Import library
    import java.awt.event.*; // Import event handling
    import java.io.*;
    import java.nio.*;
    import java.nio.charset.*;

    class gooey implements ActionListener {

        JFrame myFrame = null; // Create a JFrame, don't fill it
        JEditorPane myPane = null;
        String fileName = "myJava.java";
        Font editorFont = new Font("Consolas",Font.PLAIN, 12);

        public static void main(String[] args) {
            (new gooey()).test(); // Create a GUI and 'test' it
        }

        private void test() { // Test run of a gooey

            // FRAME
            //////////
            System.out.println("Creating myFrame..."); // Debug stuff

            myFrame = new JFrame("Gooey"); // Create a new JFrame (window)
            myFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // Set it so that when the [X] button is clicked, the app exits
            myFrame.setSize(400,300); // Set the size of 400x300px (WxH)

            System.out.println("myFrame created!"); // Debug stuff

            // MENU BAR
            /////////////
            System.out.println("Creating menuBar..."); // Debug stuff

            JMenuBar myBar = new JMenuBar(); // Create a new JMenuBar called myBar

            System.out.println("Done!"); // More debug stuff
            System.out.println("Creating JButtons...");

            JButton openButton = new JButton("Open"); // Create a button named openButton
            openButton.addActionListener(this);

            JButton saveButton = new JButton("Save"); // Create a button named saveButton
            saveButton.addActionListener(this);

            JButton quitButton = new JButton("Quit"); // Create a button named quitButton
            quitButton.addActionListener(this); // Add an actionListener

            myBar.add(openButton); // Add the buttons to the menubar
            myBar.add(saveButton);
            myBar.add(quitButton);

            System.out.println("Done!"); // Even more debug stuff

            // EDITOR PANE
            ////////////////
            System.out.println("Creating myPane..."); // EVEN MOAR DEBUG

            JEditorPane myPane = new JEditorPane(); // Create a new JEditorPane called myPane
            myPane.setContentType("text/plain"); // Set it so that it can only edit plain text
            myPane.setFont(editorFont);
            myPane.setText(
                 "This is a JEditorPane."
                +"\nIt can display text/rich text/HTML that can be edited."); // Set the starting text of myPane to that

            System.out.println("Done!"); // And yet more debug stuff

            // RUNNING IT
            ///////////////
            System.out.println("Running it all..."); // DEBUG

            myFrame.setJMenuBar(myBar); // Set the frame's menu bar to myBar
            myFrame.setContentPane(myPane); // Set it so that the content in myFrame is myPane
            myFrame.setVisible(true); // Make myFrame visible

            System.out.println("myFrame has been created!");
        }

        // ACTION LISTENERS
        /////////////////////

        public void actionPerformed(ActionEvent e) {

        // Basically, every time an action is performed (e.g. left mouse click) 
        // on something with an actionListener attached to it, we can call this
        // method.

            if (e.getActionCommand()=="Quit") System.exit(0); // If the string of the thing we're listening to was "quit", exit the program!
            else {

                // CREATE A FILE CHOOSER
                /////////////////////////
                JFileChooser myFileChoose = new JFileChooser();
                myFileChoose.setCurrentDirectory(new File("C:"));
                myFileChoose.setSelectedFile(new File(fileName));
                myFileChoose.setFileSelectionMode(JFileChooser.FILES_ONLY);

                FileNameExtensionFilter myFilter = new FileNameExtensionFilter(".java files","java");
                myFileChoose.setFileFilter(myFilter);

                try {
                    // OPEN COMMAND
                    /////////////////
                    if (e.getActionCommand()=="Open") {
                        int r = myFileChoose.showOpenDialog(myPane);                        // Create a file chooser
                        if (r == JFileChooser.APPROVE_OPTION) {                         // If the user has selected a file
                            File selectedFile = myFileChoose.getSelectedFile();             // Find that file
                            fileName = selectedFile.getName();                      // Get it's name and store it in a variable
                            FileInputStream fis = new FileInputStream(selectedFile);            // Stream the input
                            InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));   // Read said stream
                            char[] buffer = new char[1024];                         // Create a buffer
                            int n = isr.read(buffer);                           // Read from the input and buffer
                            String text = new String(buffer, 0, n);                     // Put into string
                            myPane.setText(text);                               // Put into JEditorPane
                            isr.close();
                        }
                    // SAVE COMMAND
                    /////////////////
                    } else if (e.getActionCommand()=="Save") {
                        int r = myFileChoose.showOpenDialog(myPane);
                        if (r == JFileChooser.APPROVE_OPTION) {                             // If the user has selected a file
                            File selectedFile = myFileChoose.getSelectedFile();                 // Find that file
                            fileName = selectedFile.getName();                          // Get it's name and store it in a variable
                            FileOutputStream fos = new FileOutputStream(selectedFile);              // Stream the input
                            OutputStreamWriter osr = new OutputStreamWriter(fos, Charset.forName("UTF-8"));     // Read said stream
                            osr.write(myPane.getText());
                            osr.close();
                        }
                    }
                } catch (Exception q) {
                    q.printStackTrace(); 
                }
            }
        }

    }

I try to make it work, however when I try to open or save a file via a JFileChooser, it shows me these:

Open file error:

java.lang.NullPointerException at gooey.actionPerformed(gooey.java:120)

Save file error:

java.lang.NullPointerException at gooey.actionPerformed(gooey.java:132)

The variable myPane is not initialized ( null ). This causes the NullPointerException .

You create a new JEditorPane (around line 65) but assign it to a local variable, so the class member with the same name is still null (and actionPerformed uses the class member variable myPane ). Change line 65

JEditorPane myPane = new JEditorPane(); 

to

myPane = new JEditorPane(); 

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