【问题标题】:How to count how many words Are in text Area in Java GUI Program [closed]如何计算Java GUI程序中文本区域中有多少单词[关闭]
【发布时间】:2018-05-14 20:00:28
【问题描述】:

我正在尝试制作一个程序来计算文本文件中有多少单词。我的目标是,一旦文本在 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 has x number of words”

【问题讨论】:

标签: java swing jtextarea


【解决方案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);
        }

    }

}

会输出这样的东西...

【讨论】:

  • //决定这样做但是//当没有行时它读为一行private void countWords() {String text=textArea.getText ();int countWord=text.split("\\s").length;textArea.setText("Number of Words : "+countWord);
  • 最后一个问题,当我尝试计算并清空字段时,它仍然计算它我该如何解决这个问题。我的意思是尝试在没有任何文本的情况下计算它并输出 1。
  • 首先,将String的前导/尾随空格(String#trim)剪掉,然后检查生成的String的长度,如果是0,则它没有字
  • 如果您使用 \s+ 而不是 \s 作为正则表达式,它将不会计算新行,从而为您提供更准确的结果。
  • @Tymek 需要驱动器,但由于问题本身有些模糊,所以答案也是如此;)
【解决方案2】:

首先从 textarea 中获取值

String text=textArea.getText ();

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

int countWord=text.length();

现在在控制台打印

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

【讨论】:

  • 那将是字符数
猜你喜欢
  • 1970-01-01
  • 2012-04-21
  • 2013-01-20
  • 2012-05-12
  • 1970-01-01
  • 1970-01-01
  • 2022-01-26
  • 2011-05-16
  • 1970-01-01
相关资源
最近更新 更多