动态TextArea但无法正确显示

时间:2013-05-23 01:43:37

标签: 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[] textComp2;

            JLabel coba_ah;
            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");
                    coba();
                    makeActionsPretty();

                    Container content = getContentPane();
                    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
            public void coba () {
                    if(count==0) {
                            textComp2 = new JTextComponent[1];
                            textComp2[0] = createTextComponent();
                            count+=1;
                            JOptionPane.showMessageDialog(SimpleEditor.this,
                                            count, "ERROR", JOptionPane.ERROR_MESSAGE);
                    }
                    else {
                            JTextComponent[] texttemp;
                            texttemp = new JTextComponent[count];
                            for(int i=0;i<count;i++) {
                                    texttemp[i] = createTextComponent();
                                    texttemp[i].setText(textComp2[i].getText());
                                    JOptionPane.showMessageDialog(SimpleEditor.this,
                                                    "count = " + count, "ERROR", JOptionPane.ERROR_MESSAGE);
                                    JOptionPane.showMessageDialog(SimpleEditor.this,
                                                    "textComp2[" + i + "]" + " = " + textComp2[i].getText(), "ERROR", JOptionPane.ERROR_MESSAGE);
                                    JOptionPane.showMessageDialog(SimpleEditor.this,
                                                    "texttemp[" + i + "]" + " = " + texttemp[i].getText(), "ERROR", JOptionPane.ERROR_MESSAGE);
                            }
                            count+=1;
                            textComp2 = new JTextComponent[count];
                            for(int i=0;i<count-1;i++) {
                                    textComp2[i] = createTextComponent();
                                    textComp2[i].setText(texttemp[i].getText());
                                    JOptionPane.showMessageDialog(SimpleEditor.this,
                                                    "masuk", "ERROR", JOptionPane.ERROR_MESSAGE);
                                    JOptionPane.showMessageDialog(SimpleEditor.this,
                                                    "count = " + count, "ERROR", JOptionPane.ERROR_MESSAGE);
                                    JOptionPane.showMessageDialog(SimpleEditor.this,
                                                    "textComp2[" + i + "]" + " = " + textComp2[i].getText(), "ERROR", JOptionPane.ERROR_MESSAGE);
                                    JOptionPane.showMessageDialog(SimpleEditor.this,
                                                    "texttemp[" + i + "]" + " = " + texttemp[i].getText(), "ERROR", JOptionPane.ERROR_MESSAGE);
                            }
                            textComp2[count-1] = createTextComponent();
                            JOptionPane.showMessageDialog(SimpleEditor.this,
                                            "count = " + count, "ERROR", JOptionPane.ERROR_MESSAGE);
                    }
            }

            // Create the JTextComponent subclass.
            protected JTextComponent createTextComponent() {
                    JTextArea ta = new JTextArea();
                    if (count%2==0)
                            ta.setForeground(Color.red);
                    else
                            ta.setForeground(Color.WHITE);
                    ta.setFont(new Font("Courier New",Font.PLAIN,12));
                    ta.setLineWrap(true);                                                                                                                           
                    ta.setWrapStyleWord(true);  
                    ta.addKeyListener(new java.awt.event.KeyAdapter() {
                            public void keyPressed(java.awt.event.KeyEvent ev) {
                                    taKeyPressed(ev);
                            }
                    });
                    ta.setSize(10, 10);

                    return ta;
            }

            private void taKeyPressed(java.awt.event.KeyEvent ev) { 
                    int key = ev.getKeyCode();
                    if (key == KeyEvent.VK_ENTER) {
                            coba();
                    }
                    else if (ev.getKeyChar() == 'z') {
                            String kata;
                            kata = textComp2[count-1].getText(); 
                            JOptionPane.showMessageDialog(SimpleEditor.this,
                                            kata, "ERROR", JOptionPane.ERROR_MESSAGE);
                    }
            }

            // Add icons and friendly names to actions we care about.
            protected void makeActionsPretty() {
                    Action a;

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

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

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

每次按ENTER键,此程序都会显示一些消息。它们是:count,texttemp [i]和textComp2 [i]。我的问题是为什么在我第二次按ENTER后,textComp2的结果是空字符串?我的问题与我之前的问题相同吗?

1 个答案:

答案 0 :(得分:0)

由于textComp2 String为空,JTextComponent的结果为空,textComp2为空。确保它包含一些文字。

除此之外:不要在Swing中使用KeyListeners。它们是专为AWT设计的,并不是在所有平台上都能保持一致,并且需要关注组件。请改用Key Bindings