import jregex.*; import java.awt.*; import java.applet.*; import java.awt.event.*; public class Words extends Applet{ private static final Pattern word=new Pattern("\\w+"); Label lText=new Label("Enter a text:"); TextArea textInput=new TextArea(10,40); Button bClear=new Button("Clear text"); Label lCount=new Label("Word count:"); TextField display=new TextField(5); Button bCount=new Button("Count"); public void init(){ GridBagLayout gb=new GridBagLayout(); setLayout(gb); GridBagConstraints gbc=new GridBagConstraints(); gbc.fill=gbc.BOTH; gbc.insets=new Insets(2,4,2,4); gbc.gridwidth=gbc.RELATIVE; gb.setConstraints(lText,gbc); add(lText); gbc.gridwidth=gbc.REMAINDER; gbc.fill=gbc.NONE; gbc.anchor=gbc.EAST; gb.setConstraints(bClear,gbc); gbc.fill=gbc.BOTH; gbc.anchor=gbc.CENTER; add(bClear); gbc.weighty=1; gb.setConstraints(textInput,gbc); gbc.weighty=0; add(textInput); gbc.gridwidth=1; gbc.fill=gbc.BOTH; gb.setConstraints(lCount,gbc); add(lCount); gb.setConstraints(display,gbc); add(display); gbc.gridwidth=gbc.REMAINDER; gb.setConstraints(bCount,gbc); add(bCount); display.setEditable(false); textInput.addTextListener(new TextListener(){ public void textValueChanged(TextEvent e){ display.setText(null); } }); bClear.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ textInput.setText(null); } }); bCount.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ display.setText(String.valueOf(countWords(textInput.getText()))); } }); } private static int countWords(String s){ Matcher m=word.matcher(s); int c=0; while(m.find()){ c++; } return c; } }