如何计算 Java GUI 程序中文本区域中有多少个单词

How to count how many words Are in text Area in Java GUI Program

我正在尝试制作一个程序来计算文本文件中有多少个单词。我的目标是一旦文本在 textArea 中可见,它就可以计算其中的所有单词。

我打开 .txt 文件的代码是这样的:

Action Open = new AbstractAction("Open File") {
        @Override
        public void actionPerformed(ActionEvent e) {

            if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
                openFile(fc.getSelectedFile().getAbsolutePath());
            }
        }
    };

    public void openFile(String fileName) {
        FileReader fr = null;
        try {
            fr = new FileReader(fileName);
            textArea.read(fr, null);
            fr.close();
            setTitle(fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

我看到有人在控制台中输出单个单词,例如 =11,但我想要的是用 "fileName has x number of words"

替换 textArea 中的文本

首先从textarea获取值

String text=textArea.getText ();

现在使用长度函数获取字符串长度。

int countWord=text.length();

现在在控制台打印

System.out.println ("No of Words : "+countWord);

已更新

突然意识到我可能把问题当成了字面意思

也许你的意思更像是...

String text = // Text from the file...

int letterCount = text.length();
int wordCount = text.split("\s").length;
String result = "[insert file name here] has " + letterCount + " characters and " + wordCount + " words";

// A JTextArea you created eailer
textArea.setText(result);

原回答

but what I want is to replace the text in the textArea with "fileName has x number of words"

我不太确定这正是您的意思,但是...

(针对此要求)最好的起点是 DocumentFilter

它将允许您过滤应用于 Document/JTextArea 的文本,并将其替换为您想要的任何文本。

也许是这样的……

public class WordCounterDocumentFilter extends DocumentFilter {

    @Override
    public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
        int letterCount = text.length();
        int wordCount = text.split("\s").length;
        String result = "[insert file name here] has " + letterCount + " characters and " + wordCount + " words";
        super.replace(fb, 0, fb.getDocument().getLength(), result, attrs);
    }

}

然后可以使用这样的东西...

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.text.AbstractDocument;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new BorderLayout());
            JTextArea ta = new JTextArea(10, 20);
            add(new JScrollPane(ta));
            ta.setEditable(false);

            ((AbstractDocument)ta.getDocument()).setDocumentFilter(new WordCounterDocumentFilter());
            ta.setText("This is a bunch of text");
        }

    }

    public class WordCounterDocumentFilter extends DocumentFilter {

        @Override
        public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
            int letterCount = text.length();
            int wordCount = text.split("\s").length;
            String result = "[insert file name here] has " + letterCount + " characters and " + wordCount + " words";
            super.replace(fb, 0, fb.getDocument().getLength(), result, attrs);
        }

    }

}

这会输出这样的东西...