找出 JTextField 的文本输入中有多少个单词

Finding out how many words are in the text input of JTextField

我最难找出如何编码 JTextField 输入中有多少个单词,我设置了一个清除输入按钮,一旦我弄清楚如何找出有多少个单词有,我也可以清除它。谢谢大家,这是我的代码!

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CopyTextPanel extends JPanel
{
private JTextField input;
private JLabel output, inlabel, outlabel;
private JButton compute, clear;
private JPanel panel;

public CopyTextPanel()
{
    inlabel = new JLabel("Input Text:  ");
    outlabel = new JLabel("Text Statistics Results: ");
    input = new JTextField (" ", 25);
    output = new JLabel();
    compute = new JButton("Compute Statistics");
    compute.addActionListener (new ButtonListener());
    clear = new JButton("Clear Text");
    clear.addActionListener (new ButtonListener());
    panel = new JPanel();

    output.setPreferredSize (new Dimension(550, 30));
    panel.setPreferredSize (new Dimension(620, 100));
    panel.setBackground(Color.gray);
    panel.add(inlabel);
    panel.add(input);
    //panel.add(outlabel);
    //panel.add(output);
    panel.add(compute);
    panel.add(clear);
    panel.add(outlabel);
    panel.add(output);

    setPreferredSize (new Dimension(700, 150));
    setBackground(Color.cyan);
    add(panel);
}

private class ButtonListener implements ActionListener
{
    public void actionPerformed (ActionEvent event)
    {
        if (event.getSource()==compute)
        {
            {
                output.setText (input.getText());                     
            }
        }
        else
            input.setText("");
    }
}

对于像 inputText 中那样的一小段文本,您可以使用 split 生成一个字符串数组,将字符串分成单词,然后读取数组的长度:

String test = "um dois      tres quatro        cinco ";
String [] splitted = test.trim().split("\p{javaSpaceChar}{1,}");
System.out.println(splitted.length);

//输出5

因此,对于您的意见:

String inputText = input.getText();
String [] splitted = inputText.trim().split("\p{javaSpaceChar}{1,}");
int numberOfWords = splitted.length;