Monday, January 20, 2014

Java Program to Find and Replace Using AWT Controls

with 0 Comment
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

/*<applet code="findreplace" width=350 height=300>
</applet>*/

public class findreplace extends Applet implements ActionListener
{
StringBuffer sb;
TextField t1,t2,t3;
Button b1,b2;
String msg="";
public void init()
{
Label l1=new Label("Original String:");
Label l2=new Label("Find What");
Label l3=new Label("Replace with");
t1=new TextField(30);
t2=new TextField(30);
t3=new TextField(30);
b1=new Button("Replace");
b2=new Button("Cancel");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
String s1,s2,s3,s;
int i,len;
s1=(t1.getText()).trim();
s2=(t2.getText()).trim();
s3=(t3.getText()).trim();
len=s2.length();
i=s1.indexOf(s2);
s=ae.getActionCommand();
if(s.equals("Replace");
{
if(i!=-1)
{
sb=new StringBuffer(s1);
sb.replace(i,i+len,s3);
t1.setText(String.valueOf(sb));
msg="String is replaced";
repaint();
}
else
msg="String is not found";
repaint();
}
else
{
msg="Operation is Cancelled";
t1.setText("");
t2.setText("");
t3.setText("");
repaint();
}
}
public void paint(Grpahics g)
{
g.drawString(msg,200,200);
}
}

0 comments:

Post a Comment

Powered by Blogger.

Blog Archive