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

时间:2017-10-17 21:29:02

标签: java swing 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("");
    }
}

1 个答案:

答案 0 :(得分:4)

对于像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;