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

时间:2018-05-14 20:00:29

标签: java swing jtextarea

我正在尝试创建一个计算文本文件中有多少单词的程序。我的目标是,一旦文本在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,但我想要的是将textArea中的文本替换为“fileName有x个单词”

2 个答案:

答案 0 :(得分:1)

更新

突然意识到我可能已经把这个问题按字面意思

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

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);

原始答案

  

但我想要的是将textArea中的文本替换为" fileName包含x个单词"

我不确定你的意思是什么,但是......

最佳起点(针对此要求)为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);
        }

    }

}

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

Example output

答案 1 :(得分:0)

首先从textarea获取价值

{0^(2^n); n>0}

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

String text=textArea.getText ();

现在在控制台中打印

int countWord=text.length();