This program counts how many times a particular word appears inside a text area. JApplet class is used here to display the graphical components.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | import java.awt.*; import java.awt.event.*; import javax.swing.*; public class KeywordCounter extends JApplet{ private JTextField tfkeyword=null; private JLabel lresult=null; private JTextArea tacontent=null; private JButton bcount=null; public void init() { setSize(400,500); setLayout(new BorderLayout()); JPanel ptop=new JPanel(); ptop.setLayout(new FlowLayout()); tfkeyword=new JTextField(); tfkeyword.setColumns(10); ptop.add("North",tfkeyword); lresult=new JLabel(); ptop.add("North",lresult); getContentPane().add("North",ptop); tacontent=new JTextArea(); tacontent.setLineWrap(true); tacontent.setColumns(20); tacontent.setRows(15); getContentPane().add("Center",tacontent); bcount=new JButton("Click Me"); bcount.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String tempkeyword=tfkeyword.getText().toLowerCase(); String tempcontent=tacontent.getText().toLowerCase(); int counter=0; int indexsearch=0; while(true){ int i=tempcontent.indexOf(tempkeyword,indexsearch); if(i==-1){ break; } else{ counter++; tempcontent=tempcontent.substring(tempcontent.indexOf(tempkeyword)+tempkeyword.length()); System.out.println(indexsearch); } } lresult.setText(counter+""); } }); getContentPane().add("South",bcount); } public void destroy() { } } |
No comments:
Post a Comment