Java
Slip21
Q.1) 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. [Marks 30]
Solution
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class Replace1 extends JFrame implements ActionListener
{
static int xpos = 0;
JLabel lb1 = new JLabel(" Enter Text :: ");
JLabel lb2 = new JLabel(" Text to find :: ");
JLabel lb3 = new JLabel(" Text to replace :: ");
JLabel lb4 = new JLabel(" Result :: ");
JLabel lb5 = new JLabel("No of occurences :: ");
JTextField txtadd = new JTextField(20);
JTextField txtF = new JTextField(20);
JTextField txtR = new JTextField(20);
JTextField txtRes = new JTextField(20);
JTextField txtcnt = new JTextField(20);
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JButton btnFind = new JButton("Find");
JButton btnRes = new JButton("Replace Result");
JButton btnClr = new JButton("Clear");
int count;
Replace1()
{
setSize(500,300);
setVisible(true);
setLayout(null);
p1.setLayout(new GridLayout(5,2));
p1.setSize(350,150);
p1.add(lb1); p1.add(txtadd);
p1.add(lb2); p1.add(txtF);
p1.add(lb3); p1.add(txtR);
p1.add(lb4); p1.add(txtRes);
p1.add(lb5); p1.add(txtcnt);
p2.setLayout(new GridLayout(1,3));
p2.setSize(400,30);
btnFind.addActionListener(this);
p2.add(btnFind);
btnRes.addActionListener(this);
p2.add(btnRes);
btnClr.addActionListener(this);
p2.add(btnClr);
p1.setLocation(20,50);
add(p1);
p2.setLocation(20,200);
add(p2);
}
public void actionPerformed(ActionEvent ae)
{
int i;
if(ae.getSource()==btnClr)
{
xpos = 0;
txtadd.setText("");
txtF.setText("");
txtR.setText("");
txtRes.setText("");
txtcnt.setText("");
}
if(ae.getSource() == btnFind)
{
String F = txtF.getText();
String add = txtadd.getText();
for( i=xpos;i<add.length(); i++)
{
if(i+F.length() <= add.length())
{
String temp = add.substring(i,i+F.length());
System.out.println(temp);
if(temp.equals(F))
{
txtadd.select(i,i+F.length());
xpos = i+F.length();
// txtadd.setFocus();
System.out.println("found at : " + i);
break;
}
}
}
if( i == add.length() )
xpos = 0;
}
else
{
String F,R,Res,add;
F = txtF.getText();
R = txtR.getText();
count = 0;
add = txtadd.getText();
Res = "";
System.out.println(F + " " + R + " " + add);
for( i = 0;i<add.length();i++)
{
if(i+F.length() <= add.length())
{
String temp = add.substring(i,i+F.length());
System.out.println(temp);
if(temp.equals(F))
{
Res += R;
i = i + F.length()-1;
count++;
}
else
Res += add.charAt(i);
}
else
Res += add.charAt(i);
}
txtRes.setText(Res);
txtcnt.setText(((Integer)count).toString());
}
}
public static void main(String ar[])
{
new Replace1();
}
}
Tags:
java