简体   繁体   English

将输入添加到JTextArea到ArrayLists的ArrayList中

[英]Adding Input to JTextArea to an ArrayList of ArrayLists

My objective is to add the text from a JTextArea into an ArrayList of ArrayLists, such that each line of text inputted is saved as an ArrayList, with the words of that particular line saved as elements within the ArrayList of that line. 我的目标是将JTextArea中的文本添加到ArrayLists的ArrayList中,以便将输入的每一行文本保存为ArrayList,并将该特定行的单词另存为该行的ArrayList中的元素。 I have an idea of how to store each line of the inputted text as an element within an ArrayList, but not how to have an ArrayList of ArrayLists. 我有一个想法,如何将输入的文本的每一行存储为ArrayList中的元素,而不是如何拥有ArrayLists的ArrayList。 Could anyone point me in the right direction here? 有人可以在这里指出正确的方向吗? I would like to create a 2D ArrayList and was thinking something like this: 我想创建一个2D ArrayList并正在考虑这样的事情:

ArrayList[][] poem = new ArrayList[][];

This is what I was thinking for making an ArrayList containing each line as an element, but I would like to have each of the lines as a seperate ArrayList containing their respective words as elements: 这就是我想制作一个包含每行作为元素的ArrayList的想法,但是我想将每一行作为一个单独的ArrayList包含它们各自的单词作为元素:

JTextArea txArea = new JTextArea();
String txt = txArea.getText();
String [] arrayOfLines = txt.split("\n");
ArrayList<String> linesAsAL = new ArrayList<String>();
for(String line: arrayOfLines){
  linesAsAL.add(line);
}

In sum, I am trying to make a 2D ArrayList, where each word inputted into a JTextArea would be added into its own cell within that 2D ArrayList. 总而言之,我试图制作一个2D ArrayList,将输入到JTextArea中的每个单词添加到该2D ArrayList中自己的单元格中。

Your question doesn't have to be JTextArea -specific, so my answer won't (I'm assuming you know how to get a string from a JTextArea . Hint: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextArea.html ). 您的问题不一定是特定于JTextArea ,因此我的答案将不是(我假设您知道如何从JTextArea获取字符串。提示: http : //docs.oracle.com/javase/7/ docs / api / javax / swing / JTextArea.html )。

Here's a method to transform a String into an ArrayList<ArrayList<String>> : 这是将String转换为ArrayList<ArrayList<String>>

public static List<List<String>> linesToLinesAndWords(String lines) {
    List<List<String>> wordlists = new ArrayList<>();
    List<String> lineList = Arrays.asList(lines.split("\n"));
    for (String line : lineList) {
        wordlists.add(Arrays.asList(line.trim().split(" ")));
    }
    return wordlists;
}

After seeing your code, I also suggest you learn Java. 看完代码后,我还建议您学习Java。

The following work's 以下作品

String content = jta.getText(); //jta = Instance of JTextArea
List<List<String>> list = new ArrayList<ArrayList<String>>();
for (String line : content.split("\n"))
{
String words[] = line.split("\\s");
 list.add(new ArrayList<String>(Arrays.asList(words)));
}

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

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