简体   繁体   English

在Java中更新动态TextArea

[英]Updating dynamic TextArea in Java

I'm trying create simple text editor with dynamic Text Area in Java. 我正在尝试使用Java中的动态文本区域创建简单的文本编辑器。

The application, at the beginning, only have 1 Text Area. 该应用程序开始时只有1个文本区域。 Each time I press ENTER key, the application will create a new Text Area. 每次按ENTER键,应用程序都会创建一个新的文本区域。 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. 还有2个问题。 Each time i press ENTER key, text area will be create AND the previous Text Area get a break line. 每次按ENTER键,都会创建一个文本区域,而上一个文本区域会得到一个换行符。 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? 下一个问题:我按ENTER键而不单击新的文本区域后如何转到下一个文本区域?

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. 如果要动态创建文本区域,请使用动态存储(如ArrayList)。 Then you just add the newly created text area to the ArrayList. 然后,您只需将新创建的文本区域添加到ArrayList。 So as a class variable you create the ArrayList like: 因此,您可以像这样创建ArrayList作为类变量:

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. 我将让您看一下API,以了解如何从ArrayList中“获取”元素。

Each time i press ENTER key, text area will be create AND the previous Text Area get a break line. 每次按ENTER键,都会创建一个文本区域,而上一个文本区域会得到一个换行符。 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. Enter键的默认操作将换行符字符串添加到文本区域。 This Action still executes along with the KeyListener 该动作仍与KeyListener一起执行

So, don't use a KeyListener. 因此,请勿使用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. 有关更多信息,请参见键绑定 ,包括指向键绑定的Swing教程的链接。

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. 我认为原始代码的问题是:每次添加新组件时,它都会丢失对先前组件的引用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM