我正在與下面的分配掙扎:使用字符串方法來計算單詞
分配問:使用從所述串類的方法 ,寫一個程序,將計數其通過坯料在一個字符串分隔單詞的數目。爲了簡單起見,請使用沒有標點符號或其他空格字符的字符串(製表符,換行符等)。使用JTextArea允許用戶輸入文本並允許文本區域在必要時滾動。當用戶單擊一個按鈕來計算單詞時,計數的單詞總數將顯示在用戶無法修改的文本框中。
現在我的問題是,我沒有得到計數的數字顯示在不可編輯的文本框中。 我也有問題,在輸入屏幕中間顯示cusrsor而不是頂部。
請你指點我正確的方向。
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.text.*;
import java.util.*;
public class WordCounter extends JFrame implements ActionListener
{
//Construct a panel for the fields and buttons
JPanel fieldPanel = new JPanel();
JPanel buttonPanel = new JPanel();
//Construct labels and text boxes
JTextField screen = new JTextField(1);
JLabel wordCount = new JLabel(" Word Count = ");
JTextField words = new JTextField(3);
//Construct button
JButton countButton = new JButton("Count Words");
public static void main(String[] args)
{
WordCounter f = new WordCounter();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(500,200);
f.setTitle("Word Counter");
f.setResizable(false);
f.setLocation(200,200);
f.setVisible(true);
}
public static int getWordCount(String screen)
{
int count = 0;
for (int i = 0; i < screen.length(); i++)
{
if (screen.charAt(i) == ' ')
{
count++;
}
}
return count;
}
public WordCounter()
{
Container c = getContentPane();
c.setLayout((new BorderLayout()));
fieldPanel.setLayout(new GridLayout(1,1));
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
//add rows to panels
fieldPanel.add(screen);
//add button to panel
buttonPanel.add(countButton);
buttonPanel.add(wordCount);
buttonPanel.add(words);
//add panels to frame
c.add(fieldPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
//add functionality to button
countButton.addActionListener(this);
addWindowListener(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
int answer = JOptionPane.showConfirmDialog(null,"Are you sure you want to exit?", "File Submission",JOptionPane.YES_NO_OPTION);
if (answer == JOptionPane.YES_OPTION)
System.exit(0);
}
}
);
}
public void actionPerformed(ActionEvent e)
{
}
}
有點offtopic:使用String.split(」「),而不是你getWordCount環 – Michael 2014-11-03 18:43:30