2017-10-17 90 views
1

我最難找到如何編寫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

您的問題基本可以更好地總結爲, 「如何計算字符串中的字數」,我建議首先對該主題進行一些研究,因爲其餘代碼與解決該問題無關 – MadProgrammer

+0

您應該查看正則表達式。他們對做你正在做的事非常有用。 – luckydog32

回答

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; 
+0

令人驚歎!謝謝!我得到它的工作,現在我只是想知道我是否理解正確。我明白inputtext變量設置intput.getText();到一個字符串。我不明白爲什麼我得到一個錯誤,如果我只是把Stringp [] splitted = inputText.split(「\\ s」);爲空格,爲什麼我需要添加所有其他方法調用。再次感謝A – GonePhisin

+0

我的確謝謝你!你能幫助我更好地理解String數組,而不是僅僅輸入Stringp [] splitted = inputText.split(「\\ s」); – GonePhisin

+0

不客氣。那麼,這兩種方法在某種程度上是相似的。由於覆蓋了所有空白的情況,所以使用的解決方案更加強大。請參閱此答案以獲得更準確的響應:https://stackoverflow.com/a/4731164/3055724 – Doleron

相關問題