简体   繁体   中英

Updating dynamic TextArea in Java

I'm trying create simple text editor with dynamic Text Area in Java.

The application, at the beginning, only have 1 Text Area. Each time I press ENTER key, the application will create a new Text Area. Its work! LOL. But, when i try to change the previous text area, that text area not changed. And the problem is because my previous Text Area was already in container. So, my question is how we updating all Text Area in the container?

Look at my code:

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

    public class SimpleEditor extends JFrame {

            int count = 0;
            Container content = getContentPane();

            private JTextComponent[] textComp;

            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");
                    dinamicTA();
                    content.setLayout(new FlowLayout());

                    for(int i=0;i<count;i++) {
                            content.add(textComp[i]);
                    }

                    pack();
                    content.setSize(content.getPreferredSize());
                    pack();
            }

            //create DINAMIC TEXT AREA
            public void dinamicTA () {
                    if(count==0) {
                            textComp = new JTextComponent[1];
                            textComp[0] = createTextComponent();
                            count+=1;
                    }
                    else {
                            JTextComponent[] texttemp;
                            texttemp = new JTextComponent[count];
                            for(int i=0;i<count;i++) {
                                    texttemp[i] = createTextComponent();
                            }
                            count+=1;
                            textComp = new JTextComponent[count];
                            for(int i=0;i<count-1;i++) {
                                    textComp[i] = createTextComponent();
                                    //textComp[i].setText(texttemp[i].getText()+"wow"); <-- not working
                            }
                            textComp[count-1] = createTextComponent();
                            content.add(textComp[count-1]);
                    }
            }

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

                    ta.setColumns(15);
                    pack();
                    ta.setSize(ta.getPreferredSize());
                    pack();

                    return ta;
            }

            private void taKeyReleased(java.awt.event.KeyEvent ev) { 
                    int key = ev.getKeyCode();
                    if (key == KeyEvent.VK_ENTER) {
                            dinamicTA();

                            pack();
                            content.setSize(content.getPreferredSize());
                            pack();
                    }
            }
    }

And 2 question more. Each time i press ENTER key, text area will be create AND the previous Text Area get a break line. Do you have any idea to remove the break line? Next question: how i go to next Text Area after i press ENTER key without click new Text Area?

Sorry, too many question..hahaha. Thx before :)

Arrays are meant to be used for fixed size data structures. Your code to try to keep track of newly created text areas is too confusing and error prone. Creating new Arrays and copying the data from the old array is too confusing and error prone and unnecessary.

If you want to dynamically create a text area then use a dynamic storage like an ArrayList. Then you just add the newly created text area to the ArrayList. So as a class variable you create the ArrayList like:

ArrayList<JTextComponent> components = new ArrayList<JTextComponent>();

to add a text component you just use:

components.add(...);

I'll let you look at the API to find out how to "get" an element from the ArrayList.

Each time i press ENTER key, text area will be create AND the previous Text Area get a break line. Do you have any idea to remove the break line?

The Default Action for the Enter key adds the newline string to the text area. This Action still executes along with the KeyListener

So, don't use a KeyListener. Instead you need to replace the default Action with your custom Action. The code to do this would be something like:

Action enter = new AbstractAction()
{
    public void actionPerformed(ActionEvent e)
    {
        // add your MouseListener code here
    }
});
textArea.getActionMap().put("insert-break", enter);

See Key Bindings for more information, including a link to the Swing tutorial on Key Bindings.

For your first questions, I changed the code as `

import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;

public class SimpleEditor extends JFrame {

        /**
     * 
     */
    private static final long serialVersionUID = 1L;
        int count = 0;
        Container content = getContentPane();

        private JTextComponent[] textComp;
        // Create an editor.
        public SimpleEditor() {
                super("Swing Editor");
                dinamicTA();
                content.setLayout(new FlowLayout());

                for(int i=0;i<count;i++) {
                        content.add(textComp[i]);
                }

                pack();
                content.setSize(content.getPreferredSize());
                pack();
        }

        //create DINAMIC TEXT AREA
        public void dinamicTA () {
                if(count==0) {
                        textComp = new JTextComponent[1];
                        textComp[0] = createTextComponent();
                        count+=1;
                }
                else {
                        JTextComponent[] texttemp;
                        texttemp = textComp;
                        count+=1;
                        textComp = new JTextComponent[count];
                        for(int i=0;i<count-1;i++) {
                                textComp[i] = texttemp[i];
                                textComp[i].setText(textComp[i].getText()+"wow"); //<-- not working
                        }
                        textComp[count-1] = createTextComponent();
                        content.add(textComp[count-1]);
                        textComp[count-1].requestFocus(); //get focus
                }
        }

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

                ta.setColumns(15);
                pack();
                ta.setSize(ta.getPreferredSize());
                pack();

                return ta;
        }

        private void taKeyReleased(java.awt.event.KeyEvent ev) { 
                int key = ev.getKeyCode();
                if (key == KeyEvent.VK_ENTER) {
                        dinamicTA();
                        pack();
                        content.setSize(content.getPreferredSize());
                        pack();
                }
        }

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

`

I think the problem with the original codes is : each time when you add new components, it lost reference to the previous components.

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