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

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

最佳答案

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

关于java - 找出 JTextField 的文本输入中有多少个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46799503/

相关文章:

java - 设置 JList 不可调整大小

java - 在 JEditorPane 中突出显示

multithreading - JavaFX 的 Swing 计时器替代方案和线程管理差异

java - 如何在GUI中对私有(private)变量应用Getter/Setter方法?

Java, Swing : how do I set the maximum width of a JTextField?

java - 如何从 JFrame 获取文本

java - 在 Hibernate 3.2 中使用连接池 (c3p0-0.9.1.2) 时出现异常且应用程序无法连接 MySqL 数据库?

java - 在 Eclipse 中使用 Java 代码将数据插入到 csv 文件

java - ZipOutputStream - 压缩内容错误的文件

java - 如何使用 NetBeans 插入后自动刷新绑定(bind)到 Mysql 数据库的 JTable