I'm newbie and am trying to figure out find and replace in notepad. Here is the code for find. I am wondering how can i implement a way so that after pressing the button the dialog box doesn't close and so i can use the dialog box for next find ( like find next in notepad).
import java.awt.BorderLayout;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Scanner;
import javax.swing.*;
class TextAreaEx extends JFrame implements ActionListener,KeyListener
{
JButton button1;
JTextArea tx = new JTextArea();;
int startFrom = 0;
int offset = 0;
String find = "";
String text = "";
TextAreaEx()
{
super("My Frame");
FileInputStream fis=null;
StringBuffer sb=new StringBuffer();
try
{
Scanner scan = new Scanner(new FileReader("C:\\Users\\Sam\\Desktop\\networktools.txt"));
while (scan.hasNext())
// while there's still something to read
tx.append(scan.nextLine() + "\n"); // append
}
catch(Exception e){e.printStackTrace();}
// text = sb.toString();
text=tx.getText();
text = text.toLowerCase();
button1=new JButton("Find");
button1.addActionListener(this);
getContentPane().add(button1,BorderLayout.PAGE_START);
button1.setFocusable(false);
JScrollPane p1=new JScrollPane(tx);
getContentPane().add(p1);
JFrame.setDefaultLookAndFeelDecorated(true);
tx.addKeyListener(this);
setSize(400,400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocation(400,300);
setVisible(true);
}
public static void main(String s[]){new TextAreaEx();}
public void actionPerformed(ActionEvent e)
{
startFrom = 0;
offset = 0;
if(e.getSource()==button1)
{
find = (String)JOptionPane.showInputDialog(this,"FIND:\n","Find",JOptionPane.INFORMATION_MESSAGE,null,null,null);
find = find.toLowerCase();
findWord();
this.setVisible(true);
}
}
public void findWord()
{
offset = text.indexOf(find,startFrom);
if(offset > -1)
{
tx.setFocusable(true);
tx.select(offset,find.length()+offset );
startFrom = find.length()+offset+1;
}
else JOptionPane.showMessageDialog(this,"No (more) matches");
}
public void keyPressed(KeyEvent ke)
{
if(ke.getKeyCode() == KeyEvent.VK_F3)
{
findWord();
}
}
public void keyReleased(KeyEvent ke){}
public void keyTyped(KeyEvent ke){}
}
Thanx for the help.