Write a Java applet that that takes in a sentence from the user through a text field and append the sentence to a text area in individual line when the button labeled APPEND is clicked. When the sentence is appended to the text area, the program will also count the number of the word "the" or "The" that appeared and display the total count in another text field. Provide another button labeled CLEAR to clear the sentence input text field. The panel that contains all the GUI components should be separated in a class, while the applet that invokes this panel should be in another class.
import java.awt.*; import javax.swing.*; import java.awt.event.*; class Example { Example(){ JFrame f=new JFrame(); f.setLayout(null); JLabel label1=new JLabel("String: "); JLabel label2=new JLabel("Append: "); JLabel label3=new JLabel("Count Words: "); final JTextField text1=new JTextField(20); final JTextArea area=new JTextArea(5,20); final JTextField text2=new JTextField(20); JButton b=new JButton("Append"); JButton b1=new JButton("Clear"); b.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ String str=text1.getText(); int count=0; area.setText(str); String arr[]=str.split(" "); for(int i=0;i<arr.length;i++){ if(arr[i].equals("the")||arr[i].equals("The")){ count++; } } text2.setText(Integer.toString(count)); } }); b1.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ text1.setText(""); text2.setText(""); area.setText(""); } }); label1.setBounds(10,10,100,20); text1.setBounds(150,10,200,20); label2.setBounds(10,40,100,20); area.setBounds(150,40,200,60); label3.setBounds(10,120,100,20); text2.setBounds(150,120,200,20); b.setBounds(10,150,100,20); b1.setBounds(150,150,100,20); f.add(label1); f.add(text1); f.add(label2); f.add(area); f.add(label3); f.add(text2); f.add(b); f.add(b1); f.setVisible(true); f.setSize(400,250); } } class StringExample8{ public static void main(String[] args) { new Example(); } }
Ads