在JTextArea中插入字(文本),从存储的现有文本中,同时输入

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在JTextArea中插入字(文本),从存储的现有文本中,同时输入相关的知识,希望对你有一定的参考价值。

我希望您能帮助我解决我目前正在研究的问题。

有没有一种方法可以将一个字一个字(文本)插入到 JTextArea 从现有的文本存储(如字典),同时在文本区域输入?

应该是用 KeyTyped 或其他技术...

答案

根据 @GuillaumePolet 位于此 SO Post.

我把这段代码稍微修改了一下,这样它就可以从单词列表文件中提取10个特定的单词,并将它们显示在编辑滑块当前位置附近的弹出列表中。你可以打完字或用鼠标从弹出的列表中双击你想要的单词,也可以用光标和回车键来做同样的事情。

enter image description here

你使用的单词列表由你决定。我只是从网上复制了一个由124390个单词组成的。只要提供 dictionaryFilePath 字符串成员变量你要使用的字典文本文件的路径和文件名。这个变量位于 建议面板 内部类。这里是整个可运行的代码。

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.BadLocationException;


public class WordAssist {

public class SuggestionPanel {

    private final JList<String> list;
    private final JPopupMenu popupMenu;
    private final String subWord;
    private final int insertionPosition;

    private String dictionaryFilePath = "French_Dictionary.txt";
    private int numberOfWordsInList = 10;
    private Color colorOfList = Color.decode("#FBFEC3");  // Light-Yellow (default)
    private Color colorOfListText = Color.decode("#000000");  // Black (default)
    private String listFontName = Font.SANS_SERIF;
    private int listFontStyle = Font.PLAIN;
    private int listFontSize = 11;
    private Font listFont = new Font(listFontName, listFontStyle, listFontSize);
    private Locale locale = Locale.FRANCE;
    public String characterEncoding = "UTF-8";

    public SuggestionPanel(JTextArea textarea, int position, String subWord, Point location) {
        this.insertionPosition = position;
        this.subWord = subWord;
        popupMenu = new JPopupMenu();
        popupMenu.removeAll();
        popupMenu.setOpaque(false);
        popupMenu.setBorder(null);
        popupMenu.add(list = createSuggestionList(position, subWord), BorderLayout.CENTER);
        popupMenu.show(textarea, location.x, textarea.getBaseline(0, 0) + location.y);
    }

    public void hide() {
        popupMenu.setVisible(false);
        if (suggestion == this) {
            suggestion = null;
        }
    }

    private JList<String> createSuggestionList(final int position, final String subWord) {
        String[] data = searchForWord(dictionaryFilePath, subWord + "*", numberOfWordsInList);
        if (data.length == 0) {
            data = new String[2];
            data[0] = " : Unknown Word : ";
            data[1] = "Add To Dictionary";
        }
        JList<String> assistList = new JList<>(data);
        assistList.setFont(new Font(listFontName, listFontStyle, listFontSize));
        assistList.setBorder(BorderFactory.createLineBorder(Color.DARK_GRAY, 1));
        assistList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        assistList.setBackground(colorOfList);
        assistList.setForeground(colorOfListText);
        if (data.length == 2 && data[0].equalsIgnoreCase("unknown word:")) {
            assistList.setSelectedIndex(1);
        }
        else {
            assistList.setSelectedIndex(0);
        }
        assistList.addMouseListener(new MouseAdapter() {
            @Override
            @SuppressWarnings("Convert2Lambda")
            public void mouseClicked(MouseEvent e) {
                if (e.getClickCount() == 1 && list.getSelectedValue().equalsIgnoreCase("add to dictionary")) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            addToDictionary(dictionaryFilePath, subWord, characterEncoding, locale);
                        }
                    });
                    hideSuggestion();
                    textarea.requestFocus();
                }
                if (e.getClickCount() == 2) {
                    insertSelection();
                    hideSuggestion();
                    textarea.requestFocus();
                }
            }
        });
        return assistList;
    }

    /**
     * Adds the supplied word to the supplied Dictionary text file but only
     * if it doesn't already exist. The dictionary text file must be
     * formated in such a manner that each line of that file must contain
     * only one word.
     *
     * @param dictionaryPath    (String) The path and file name to the
     *                          Dictionary text file.<br>
     *
     * @param wordToAdd         (String) The word to add to dictionary.<br>
     *
     * @param characterEncoding (String) The Character encoding to use for Dictionary:<pre>
     *
     *         Example:  "UTF-8"</pre><br>
     *
     * See:
     * <b>https://docs.oracle.com/javase/8/docs/technotes/guides/intl/encoding.doc.html</b>
     * for all the supported Encodings.<br>
     *
     * @param locale            (Locale) The Locale of the dictionary file.
     *                          This is also important for sorting so that
     *                          it too is done according to the proper locale.<pre>
     *         Example: Locale.FRANCE or Locale.US;</pre>
     *
     */
    public void addToDictionary(String dictionaryPath, String wordToAdd, String characterEncoding, Locale locale) {
        if (dictionaryPath.trim().equals("") || wordToAdd.trim().equals("")) {
            return;
        }
        wordToAdd = wordToAdd.trim();

        String savePath = new File(dictionaryPath).getAbsolutePath();
        savePath = savePath.substring(0, savePath.lastIndexOf(File.separator))
                + File.separator + "tmpDictFile.txt";

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(dictionaryPath), characterEncoding))) {
            OutputStream os = new FileOutputStream(savePath);
            // PrintWriter writer = new PrintWriter(savePath)) {
            try (PrintWriter writer = new PrintWriter(new OutputStreamWriter(os, characterEncoding))) {
                // PrintWriter writer = new PrintWriter(savePath)) {
                String addwordFirstChar = wordToAdd.substring(0, 1);

                Collator collator = Collator.getInstance(locale);
                collator.setStrength(Collator.PRIMARY);

                List<String> wordList = new ArrayList<>();
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.equals("")) {
                        continue;
                    }
                    String firstChar = line.substring(0, 1);
                    if (firstChar.equals(firstChar.toUpperCase())
                            && addwordFirstChar.equals(addwordFirstChar.toUpperCase())
                            && collator.equals(firstChar, addwordFirstChar)) {
       

以上是关于在JTextArea中插入字(文本),从存储的现有文本中,同时输入的主要内容,如果未能解决你的问题,请参考以下文章

在 JTextArea 中设置插入符号位置

如何从JTextArea中删除旧文本,以便文档大小不超过阈值? (JAVA)

在 JTextArea 中添加边距?

更改 JTextArea 中的文本选择类型

来自 jTextPane 的可点击文本

如何使用 Puppeteer 从输入中删除现有文本?