动态简单文本编辑器 Java [英] Dynamic Simple Text Editor Java

查看:40
本文介绍了动态简单文本编辑器 Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

请看我的代码:

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)

有人能尽快帮我吗?

推荐答案

数组JTextComponent[]在不同的时间有不同的大小,但是数组中的一个对象默认为null代码>,直到您更改它:

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");

这篇关于动态简单文本编辑器 Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆