Tuesday, 21 November 2017

Corejava-Slip21

Slip21. Write a Java program to design a screen using Swing that will create four TextFields. First for the text, second for what to find and third for replace.Display result in the fourth TextField. Display the count of total no. of replacements made. The button clear to clear the TextFields.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Slip21 extends JFrame implements ActionListener
{
JLabel textlabel,findlabel,replacelabel,occurrencelabel;
JTextArea text;
JTextField findText,replaceText,occurrenceText;
JButton find,replace,exit;
JPanel pan1,pan2;
int occurrences1=0;
public Slip21()
{
textlabel=new JLabel("Enter Text:");
findlabel=new JLabel("Text to Find:");
replacelabel=new JLabel("Text to replace:");
occurrencelabel=new JLabel("No of Occurrences:");
text=new JTextArea(1,20);
findText=new JTextField(20);
replaceText=new JTextField(20);
occurrenceText=new JTextField(20);
pan1=new JPanel();
pan1.setLayout(new GridLayout(4,2));
pan1.add(textlabel);
pan1.add(text);
pan1.add(findlabel);
pan1.add(findText);
pan1.add(replacelabel);
pan1.add(replaceText);
pan1.add(occurrencelabel);
pan1.add(occurrenceText);
find=new JButton("Find");
replace=new JButton("Replace");
exit=new JButton("Exit");
find.addActionListener(this);
replace.addActionListener(this);
exit.addActionListener(this);
pan2=new JPanel();
pan2.setLayout(new FlowLayout());
pan2.add(find);
pan2.add(replace);
pan2.add(exit);
Container c=getContentPane();
c.add(pan1,"Center");
c.add(pan2,"South");
setTitle("Find and Replace:");
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String args[])
{
new Slip21();
}
public void actionPerformed(ActionEvent ae)
{
int occurrences=0;
JButton btn=(JButton)ae.getSource();
if(btn==find)
{
String s=text.getText();
f=findText.getText();
int i=0;
int len=s.length();
int cnt=0;
int j=0;
while(cnt<len)
{
i=s.indexOf(f,cnt);
if(i!=j && i>0)
{
occurrences++;
}
j=i;
cnt=cnt+1;
}
occurrenceText.setText(Integer.toString(occurrences));
}
if(btn==replace)
{
String mainText=text.getText();
String r=replaceText.getText();
String f=findText.getText();
mainText=mainText.replaceAll(f,r);
text.setText(mainText);
}
if(btn==exit)
{
System.exit(0);
}
}
}