Dynamic Simple Text Editor Java

家住魔仙堡 提交于 2019-12-24 07:46:28

问题


I have modified code from here for my project. I want to make a editor that have dynamic text area. Each time I press the enter key, a new text area will create. Sorry, I cannot explain more with English.

Please look my code:

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.io.*;
import java.awt.event.*;
import java.util.Hashtable;

public class SimpleEditor extends JFrame {

    int count = 0;
    private Action openAction = new SimpleEditor.OpenAction();
    private Action saveAction = new SimpleEditor.SaveAction();
    //private JTextComponent textComp;
    private JTextComponent[] textComp2;
    //private Hashtable actionHash = new Hashtable();

    public static void main(String[] args) {
        SimpleEditor editor = new SimpleEditor();
        editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        editor.setVisible(true);
    }

    // Create an editor.
    public SimpleEditor() {
        super("Swing Editor");
        //textComp = createTextComponent(); 
        coba();
        makeActionsPretty();

        Container content = getContentPane();
        //content.add(textComp, BorderLayout.CENTER);
        for (int i = 0; i < count; i++) {
            content.add(textComp2[i], BorderLayout.CENTER);
        }
        content.add(createToolBar(), BorderLayout.NORTH);
        setJMenuBar(createMenuBar());
        setSize(320, 240);
    }

    //coba-coba
    protected void coba() {
        if (count == 0) {
            textComp2 = new JTextComponent[1];
            count += 1;
        } else {
            JTextComponent[] texttemp;
            texttemp = new JTextComponent[count];
            for (int i = 0; i < count; i++) {
                texttemp[i] = createTextComponent();
                texttemp[i] = textComp2[i];
            }
            count += 1;
            textComp2 = new JTextComponent[count];
            for (int i = 0; i < count - 1; i++) {
                textComp2[i] = createTextComponent();
                textComp2[i] = texttemp[i];
            }
        }
    }

    // Create the JTextComponent subclass.
    protected JTextComponent createTextComponent() {
        JTextArea ta = new JTextArea();
        ta.setFont(new Font("Courier New", Font.PLAIN, 12));
        ta.setLineWrap(true);
        ta.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent ev) {
                taKeyPressed(ev);
            }
        });
        return ta;
    }

    private void taKeyPressed(java.awt.event.KeyEvent ev) {
        if (ev.getKeyCode() == 13) {
            coba();
        }
    }

    // Add icons and friendly names to actions we care about.
    protected void makeActionsPretty() {
        Action a;
        /*a = textComp.getActionMap().get(DefaultEditorKit.cutAction);
         a.putValue(Action.SMALL_ICON, new ImageIcon("icons/cut.gif"));
         a.putValue(Action.NAME, "Cut");

         a = textComp.getActionMap().get(DefaultEditorKit.copyAction);
         a.putValue(Action.SMALL_ICON, new ImageIcon("icons/copy.gif"));
         a.putValue(Action.NAME, "Copy");

         a = textComp.getActionMap().get(DefaultEditorKit.pasteAction);
         a.putValue(Action.SMALL_ICON, new ImageIcon("icons/paste.gif"));
         a.putValue(Action.NAME, "Paste");

         a = textComp.getActionMap().get(DefaultEditorKit.selectAllAction);
         a.putValue(Action.NAME, "Select All");*/

        for (int i = 0; i < count; i++) {
            a = textComp2[i].getActionMap().get(DefaultEditorKit.cutAction);
            a.putValue(Action.SMALL_ICON, new ImageIcon("icons/cut.gif"));
            a.putValue(Action.NAME, "Cut");

            a = textComp2[i].getActionMap().get(DefaultEditorKit.copyAction);
            a.putValue(Action.SMALL_ICON, new ImageIcon("icons/copy.gif"));
            a.putValue(Action.NAME, "Copy");

            a = textComp2[i].getActionMap().get(DefaultEditorKit.pasteAction);
            a.putValue(Action.SMALL_ICON, new ImageIcon("icons/paste.gif"));
            a.putValue(Action.NAME, "Paste");

            a = textComp2[i].getActionMap().get(DefaultEditorKit.selectAllAction);
            a.putValue(Action.NAME, "Select All");
        }
    }

    // Create a simple JToolBar with some buttons.
    protected JToolBar createToolBar() {
        JToolBar bar = new JToolBar();

        // Add simple actions for opening & saving.
        bar.add(getOpenAction()).setText("");
        bar.add(getSaveAction()).setText("");
        bar.addSeparator();

        // Add cut/copy/paste buttons.
              /*bar.add(textComp.getActionMap().get(DefaultEditorKit.cutAction)).setText("");
         bar.add(textComp.getActionMap().get(
         DefaultEditorKit.copyAction)).setText("");
         bar.add(textComp.getActionMap().get(
         DefaultEditorKit.pasteAction)).setText("");*/

        for (int i = 0; i < count; i++) {
            bar.add(textComp2[i].getActionMap().get(DefaultEditorKit.cutAction)).setText("");
            bar.add(textComp2[i].getActionMap().get(
                DefaultEditorKit.copyAction)).setText("");
            bar.add(textComp2[i].getActionMap().get(
                DefaultEditorKit.pasteAction)).setText("");
        }
        return bar;
    }

    // Create a JMenuBar with file & edit menus.
    protected JMenuBar createMenuBar() {
        JMenuBar menubar = new JMenuBar();
        JMenu file = new JMenu("File");
        JMenu edit = new JMenu("Edit");
        menubar.add(file);
        menubar.add(edit);

        file.add(getOpenAction());
        file.add(getSaveAction());
        file.add(new SimpleEditor.ExitAction());
        /* edit.add(textComp.getActionMap().get(DefaultEditorKit.cutAction));
         edit.add(textComp.getActionMap().get(DefaultEditorKit.copyAction));
         edit.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction));
         edit.add(textComp.getActionMap().get(DefaultEditorKit.selectAllAction));*/

        for (int i = 0; i < count; i++) {
            edit.add(textComp2[i].getActionMap().get(DefaultEditorKit.cutAction));
            edit.add(textComp2[i].getActionMap().get(DefaultEditorKit.copyAction));
            edit.add(textComp2[i].getActionMap().get(DefaultEditorKit.pasteAction));
            edit.add(textComp2[i].getActionMap().get(DefaultEditorKit.selectAllAction));
        }
        return menubar;
    }

    // Subclass can override to use a different open action.
    protected Action getOpenAction() {
        return openAction;
    }

    // Subclass can override to use a different save action.
    protected Action getSaveAction() {
        return saveAction;
    }

    //protected JTextComponent getTextComponent() { return textComp; }
    // ********** ACTION INNER CLASSES ********** //
    // A very simple exit action
    public class ExitAction extends AbstractAction {

        public ExitAction() {
            super("Exit");
        }

        public void actionPerformed(ActionEvent ev) {
            System.exit(0);
        }
    }

    // An action that opens an existing file
    class OpenAction extends AbstractAction {

        public OpenAction() {
            super("Open", new ImageIcon("icons/open.gif"));
        }

        // Query user for a filename and attempt to open and read the file into the
        // text component.
        public void actionPerformed(ActionEvent ev) {
            JFileChooser chooser = new JFileChooser();
            if (chooser.showOpenDialog(SimpleEditor.this)
                != JFileChooser.APPROVE_OPTION) {
                return;
            }
            File file = chooser.getSelectedFile();
            if (file == null) {
                return;
            }

            FileReader reader = null;
            try {
                reader = new FileReader(file);
                //textComp.read(reader, null);
                for (int i = 0; i < count; i++) {
                    textComp2[i].read(reader, null);
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(SimpleEditor.this,
                    "File Not Found", "ERROR", JOptionPane.ERROR_MESSAGE);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException x) {
                    }
                }
            }
        }
    }

    // An action that saves the document to a file
    class SaveAction extends AbstractAction {

        public SaveAction() {
            super("Save", new ImageIcon("icons/save.gif"));
        }

        // Query user for a filename and attempt to open and write the text
        // component’s content to the file.
        public void actionPerformed(ActionEvent ev) {
            JFileChooser chooser = new JFileChooser();
            if (chooser.showSaveDialog(SimpleEditor.this)
                != JFileChooser.APPROVE_OPTION) {
                return;
            }
            File file = chooser.getSelectedFile();
            if (file == null) {
                return;
            }

            FileWriter writer = null;
            try {
                writer = new FileWriter(file);
                //textComp.write(writer);
                for (int i = 0; i < count; i++) {
                    textComp2[i].write(writer);
                }
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(SimpleEditor.this,
                    "File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException x) {
                    }
                }
            }
        }
    }
}

But, my code have some error like this:

Exception in thread "main" java.lang.NullPointerException
- at SimpleEditor.makeActionsPretty(SimpleEditor.java:101)
- at SimpleEditor.<init>(SimpleEditor.java:29)
- at SimpleEditor.main(SimpleEditor.java:19)

Can anybody help me as soon as possible?


回答1:


The array JTextComponent[] has different sizes at different times, but an object in the array defaults to null until you change it:

textComp2[i] = new JTextField("Hello");


来源:https://stackoverflow.com/questions/16687812/dynamic-simple-text-editor-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!