动态简单文本编辑器Java

时间:2013-05-22 09:09:06

标签: java swing textarea text-editor

我已为我的项目修改了here的代码。 我想制作一个具有动态文本区域的编辑器。每次按下回车键,都会创建一个新的文本区域。对不起,我无法用英语解释更多。

请查看我的代码:

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) {
                    }
                }
            }
        }
    }
}

但是,我的代码有这样的错误:

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)

有人可以尽快帮助我吗?

1 个答案:

答案 0 :(得分:1)

数组JTextComponent[]在不同时间有不同的大小,但是在更改之前,数组中的对象默认为null

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