• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

Implementing function in new dialog

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,
Im only a beginner at Java and im currently modifying a texteditor. Ive already added a print dialog displaying random numbers.
Im having trouble implementing a Find/Replace function in my texteditor. The code at the moment for the find replace mechanism is searching the .java file. Could someone please show me how to implement this in the text field on the editor...
Here is the code for both of the apps.Much appreciated

/////////////////////SimpleTextEditor//////////////////


import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.BevelBorder;
import javax.swing.text.*;
import javax.swing.text.rtf.*;
import javax.swing.event.*;
import javax.swing.filechooser.*;
import javax.swing.undo.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.beans.*;

public class SimpleTextEditor extends JFrame
{
//Required variables
private JTextPane textpane;
private JMenuBar mb;
private JFileChooser chooser;
private Hashtable actions;
private JPopupMenu popup;
private JMenuItem exit, newDoc, save, open, saveAs, print;
private StyledEditorKit edkit;
private RTFEditorKit rtfkit;
private DefaultStyledDocument doc;
private MyDocumentListener doclistener;

//Useful variables
private String filename = "untitled1.txt",filetype = ".txt";
private File thisfile;
protected String FileFormats[],FileDescriptions[];
protected boolean DocumentIsUnedited = true, DocumentIsSaved = false;
public String newline = "\n";

// These are the actions used in the menus and on the toolbar
protected Action bold, italic, underline, alignleft, alignright, aligncentre;
protected Action cut, copy, paste, tools[];


public SimpleTextEditor()
{
//Sets up the main document frame
super("SimpleTextEditor - untitled1.txt");
this.setLocation(200, 200);
getContentPane().setLayout(new BorderLayout());

//Set up the file formats and file choosers etc
FileFormats = new String[]{".rtf", ".txt", ".java", ".bat"};
FileDescriptions = new String[]{"Rich Text Format Files", "Text Files", "Java Source Files", "DOS Batch Files"};

chooser = new JFileChooser();
javax.swing.filechooser.FileFilter defaultFilter = new SimpleFilter(FileFormats[0], FileDescriptions[0]);

for (int i = 1; i < FileFormats.length; i++)
{
chooser.addChoosableFileFilter(new SimpleFilter(FileFormats[i], FileDescriptions[i]));
}

File working = new File("C:/Documents");
if (!working.exists())
{
working = new File("C:/MyDocuments");
if (!working.exists()) working = new File("C:/");
}

// Set up Document object and Editor kits
doc = new DefaultStyledDocument();
edkit = new StyledEditorKit();
rtfkit = new RTFEditorKit();

// Set up Listener objects
doclistener = new MyDocumentListener();
doc.addDocumentListener(doclistener);

//Set up main GUI content
textpane = new JTextPane(doc);
textpane.setPreferredSize(new Dimension(400, 400));
textpane.setMinimumSize(new Dimension(400, 400));

JScrollPane scroller = new JScrollPane(textpane);
scroller.setPreferredSize(new Dimension(400, 400));

// Create the menu bar
mb = new JMenuBar();
JMenu File = new JMenu("File");

//Sort out Actions etc
createActionTable(textpane);
createToolbarActions();
JMenu Style = createStyleMenu();

//Create Edit menu
JMenu Edit = createEditMenu();

// set up main menu items with ActionListeners

//New Document (Menu entry)
newDoc = new JMenuItem("New");
newDoc.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
newDoc();
}
});

//Exit the app (Menu entry)
exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
exit();
}
});

//Prints the current file (Menu entry)
print = new JMenuItem("Print");
print.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
print();
}
});

//Saves the active file (Menu entry)
save = new JMenuItem("Save");
save.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
save();
}
});

//saving the file to a name (Menu entry)
saveAs = new JMenuItem("Save As...");
saveAs.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
saveas();
}
});

//opens a file (Menu entry)
open = new JMenuItem("Open...");
open.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
open();
}
});

// Create the popup menu
popup = createEditMenu().getPopupMenu();
popup.addSeparator();
popup.add(createStyleMenu());
textpane.add(popup);

// set up File menus
File.add(newDoc);
File.add(open);
File.add(print);
File.add(save);
File.add(saveAs);
File.addSeparator();
File.add(exit);

// add the menus to the menubar
mb.add(File);
mb.add(Edit);
mb.add(Style);
this.setJMenuBar(mb);
getContentPane().add("Center", scroller);

// Add mouse Listener to the textpane for popup events i.e for highlighting lines and opening a quick box
textpane.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent e)
{
if (e.isPopupTrigger())
{
popup.show(textpane, e.getX(), e.getY());
e.consume();
}
}

public void mouseReleased(MouseEvent e)
{
if (e.isPopupTrigger())
{
popup.show(textpane, e.getX(), e.getY());
e.consume();
}
}
});
}

//Main active methods

// Main Exit method
public void exit()
{
if (DocumentIsUnedited)
{//Check that document is saved/unedited etc
dispose();
setVisible(false);
System.exit(0);
}
else
{
switch (showNotSavedDialog("Exit"))
{
case JOptionPane.YES_OPTION:
save();
exit();
break;
case JOptionPane.NO_OPTION:
DocumentIsUnedited = true;
exit();
break;
case JOptionPane.CANCEL_OPTION:
break;
}
}
}

//Method to create new documents
public void newDoc()
{
//if the doc is unedited continue as normal, else show save options
if (DocumentIsUnedited)
{
initDoc();
filename = "untitled.txt";
filetype = ".txt";
resetTitle();
}
else
{
switch (showNotSavedDialog("New Document"))
{
case JOptionPane.YES_OPTION:
save();
newDoc();
break;
case JOptionPane.NO_OPTION:
DocumentIsUnedited = true;
newDoc();
break;
case JOptionPane.CANCEL_OPTION:
break;
}
}
}

// Helper method to initialize a new document
private void initDoc()
{
doc = null;
doc = (DefaultStyledDocument) edkit.createDefaultDocument();
doc.addDocumentListener(doclistener);
textpane.setStyledDocument(doc);
}

//Kicks off the timer which will then be used to spout out random numbers
public void print()
{
new TimerTestDialog(this);
}

//This sets up the timer to control the random numbers
class TimerTestDialog extends JDialog
{
TimerTestDialog(Frame parent)
{
super(parent, "Printing...");
setLocationRelativeTo(parent);
setupDialog();
setModal(false); // this will allow you to do still stuff with the main frame
Timer t = new Timer(2000, ticker);
t.start();
}

//sets up the printing box
private void setupDialog()
{
Container c = getContentPane();
c.setLayout(new BorderLayout());

c.add(getDisplayPanel(), BorderLayout.CENTER);
c.add(getButtonPanel(), BorderLayout.SOUTH);

setSize(200, 125);
setVisible(true);
}

//Populates the panel and displays it
private Component getDisplayPanel()
{
label = new JLabel("PRINTING", JLabel.CENTER);
label.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JPanel backing = new JPanel(new BorderLayout());

backing.add(label, BorderLayout.NORTH); // this will ensure the label doesn't go all tall
panel.add(backing, BorderLayout.CENTER);

return panel;
}

//creates the close button on the panel
private Component getButtonPanel()
{
JPanel panel = new JPanel(new BorderLayout());
panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JPanel backing = new JPanel(new BorderLayout());
JButton closeButton = new JButton("close");
closeButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
dispose();
}
});
backing.add(closeButton, BorderLayout.NORTH);
panel.add(backing, BorderLayout.EAST);

return panel;
}

//listens for the ticker to change the random number to display it
private ActionListener ticker = new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
label.setText(String.valueOf(getRandomNumber()));
}
};

//controls the random number
private int getRandomNumber()
{
return r.nextInt(1000) + 1;
}
private JLabel label;
};

private static Random r = new Random();

//this is the code for the Save As component
public void saveas()
{
int n = chooser.showSaveDialog(this);
if (n == 0)
{
filename = chooser.getSelectedFile().getName();
boolean ext = false;
setFiletype();
thisfile = new File(chooser.getCurrentDirectory(), filename);
DocumentIsSaved = true;
save();
resetTitle();
}
repaint();
}

//this is the code for the Save componant, this will use Save As if there is no name for the doc
public void save()
{
if (DocumentIsSaved)
{
try
{
FileOutputStream out = new FileOutputStream(thisfile);
if ((filetype.equals(".rtf")) || (filetype.equals(".doc")))
{
rtfkit.write(out, doc, 0, doc.getLength());
}
else
edkit.write(out, doc, 0, doc.getLength());
}
catch (Exception e)
{
System.out.println("" + e.getMessage() + "");
}
DocumentIsUnedited = true;
}
else
saveas();
}

//this is the code for the "open" componant
public void open()// Find a file and read it into the document
{
if (DocumentIsUnedited)
{
int n = chooser.showOpenDialog(this); // get the outcome of the dialog
if (n == 0)
{
File file = chooser.getSelectedFile();
filename = chooser.getName(file);
setFiletype();
resetTitle();
initDoc();
try
{
FileInputStream in = new FileInputStream(file);
if (filetype.equals(".rtf"))
{
rtfkit.read(in, doc, 0);
}
edkit.read(in, doc, 0);
}
catch (Exception e)
{
System.out.println("" + e.getMessage() + "");
}

thisfile = new File(chooser.getCurrentDirectory(), chooser.getSelectedFile().getName());
DocumentIsUnedited = true;
DocumentIsSaved = true;
resetTitle();
}
repaint();
}
else
{
switch (showNotSavedDialog("Open"))
{
case JOptionPane.YES_OPTION:
save();
open();
break;
case JOptionPane.NO_OPTION:
DocumentIsUnedited = true;
open();
break;
case JOptionPane.CANCEL_OPTION:
break;
}
}
}

// Helper method to get the filetype of saved/opened documents
private void setFiletype()
{
filetype = null;
for (int i = 0; i < FileFormats.length; i++)
{

if (filename.toLowerCase().endsWith(FileFormats[i]))
filetype = FileFormats[i];
else
{
for (i = 0; i < filename.length(); i++)
{
if (filename.toLowerCase().charAt(i) == '.')
{
filetype = filename.substring(i);
}
}
}
if (filetype == null) filetype = ".txt";
}
}

private void resetTitle()
{
this.setTitle("SimpleTextEditor - " + filename);
}

// Helper method to create "Save? Yes/No/Cancel" dialogs
private int showNotSavedDialog(String title)
{
int n = JOptionPane.showConfirmDialog(this, "The last document has not been saved. \nDo you want to save it first?",
title,
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
return n;
}

//This code listens to the document which is then used to decide weather the save code needs to be run
protected class MyDocumentListener implements DocumentListener
{
public void insertUpdate(DocumentEvent e)
{
SimpleTextEditor.this.DocumentIsUnedited = false;
}

public void removeUpdate(DocumentEvent e)
{
SimpleTextEditor.this.DocumentIsUnedited = false;
}

public void changedUpdate(DocumentEvent e)
{
SimpleTextEditor.this.DocumentIsUnedited = false;
}
}

//Helper class for FileFilter, allows a description to be assigned to a filetype
protected class SimpleFilter extends javax.swing.filechooser.FileFilter
{
String type,des;

public SimpleFilter(String type, String des)
{
this.des = des;
this.type = type;
}

public boolean accept(File f)
{
if (f.isDirectory())
return true;
else
{
if (f.getName().toLowerCase().endsWith(type))
return true;
else
return false;
}
}

public String getDescription()
{
return des;
}
}

//Method to help create style menu
protected JMenu createStyleMenu()
{
JMenu menu = new JMenu("Style");
menu.add(bold);
menu.add(italic);
menu.add(underline);

menu.addSeparator();
menu.add(new StyledEditorKit.FontSizeAction("12", 12));
menu.add(new StyledEditorKit.FontSizeAction("14", 14));
menu.add(new StyledEditorKit.FontSizeAction("18", 18));
return menu;
}

//Method to help create edit menu
protected JMenu createEditMenu()
{
JMenu menu = new JMenu("Edit");
menu.add(cut);
menu.add(copy);
menu.add(paste);

menu.addSeparator();

Action selectall = getActionByName(DefaultEditorKit.selectAllAction);
selectall.putValue(Action.NAME, "Select All");
menu.add(selectall);
return menu;
}

public void createToolbarActions()
{
bold = new StyledEditorKit.BoldAction();
bold.putValue(Action.NAME, "Bold");
italic = new StyledEditorKit.ItalicAction();
italic.putValue(Action.NAME, "Italic");
underline = new StyledEditorKit.UnderlineAction();
underline.putValue(Action.NAME, "Underline");
cut = getActionByName(DefaultEditorKit.cutAction);
cut.putValue(Action.NAME, "Cut");
copy = getActionByName(DefaultEditorKit.copyAction);
copy.putValue(Action.NAME, "Copy");
paste = getActionByName(DefaultEditorKit.pasteAction);
paste.putValue(Action.NAME, "Paste");
alignleft = new StyledEditorKit.AlignmentAction("Left Justify", StyleConstants.ALIGN_LEFT);
alignright = new StyledEditorKit.AlignmentAction("Right Justify", StyleConstants.ALIGN_RIGHT);
aligncentre = new StyledEditorKit.AlignmentAction("Align Centre", StyleConstants.ALIGN_CENTER);
tools = new Action[]{cut, copy, paste, bold, italic, underline};
}

// helper methods to enable menu creators to get their actions by name
private void createActionTable(JTextComponent textComponent)
{
actions = new Hashtable();
Action[] actionsArray = textComponent.getActions();
for (int i = 0; i < actionsArray.length; i++)
{
Action a = actionsArray[i];
actions.put(a.getValue(Action.NAME), a);
}
}

private Action getActionByName(String name)
{
return (Action) (actions.get(name));
}

// Obligatory main method...
public static void main(String[] args)
{
final SimpleTextEditor f = new SimpleTextEditor();

//make sure Window events are dealt with
f.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
f.exit();
}
});
f.pack();
f.setVisible(true);
}
}

//////////////////////////////FindReplace///////////////////////

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.border.*;

/**
*/
public class FindReplace extends JDialog implements ActionListener
{
private final static int TEXT_FIELD_SIZE = 20;
private final static int COMPONENT_GAP = 10;
private final static Border EMPTY_BORDER = new EmptyBorder(5, 5, 5, 5);

// Shared instance of this class

private static FindReplace sharedFindReplace;

// Visible components on the dialog

private JLabel findLabel;
private JLabel replaceLabel;
private JTextField findData;
private JTextField replaceData;
private JCheckBox matchCase;
private JCheckBox matchWord;
private JRadioButton searchUp;
private JRadioButton searchDown;
private JButton findNextButton;
private JButton closeButton;
private JButton replaceButton;
private JButton replaceAllButton;
private JPanel findPanel;
private JPanel replacePanel;
private JPanel optionPanel;
private JPanel commandPanel;

// Component to search
private JTextComponent textComponent;

// Starting position of search
private Position searchStartPosition;

// Has the search wrapped
private boolean searchWrap;

private Frame owner;
/*
public Window getOwner()
{
System.out.println("here");
return owner;
}
*/
public FindReplace(Frame owner)
{
super( owner );
this.owner = owner;
setDefaultCloseOperation( JDialog.HIDE_ON_CLOSE );
setResizable( false );

// Create find panel

findData = new JTextField( TEXT_FIELD_SIZE );
findData.setMaximumSize( findData.getPreferredSize() );

findLabel = new JLabel( "Find what:" );
findLabel.setDisplayedMnemonic( 'N' );
findLabel.setLabelFor( findData );

findPanel = new JPanel();
findPanel.setBorder( EMPTY_BORDER );
findPanel.setLayout( new BoxLayout(findPanel, BoxLayout.X_AXIS) );
findPanel.add( findLabel );
findPanel.add( Box.createHorizontalGlue() );
findPanel.add( Box.createHorizontalStrut( COMPONENT_GAP ) );
findPanel.add( findData );

// Create replace panel

replaceData = new JTextField( TEXT_FIELD_SIZE );
replaceData.setMaximumSize( findData.getPreferredSize() );

replaceLabel = new JLabel( "Replace with:" );
replaceLabel.setDisplayedMnemonic( 'P' );
replaceLabel.setLabelFor( replaceData );

replacePanel = new JPanel();
replacePanel.setBorder( EMPTY_BORDER );
replacePanel.setLayout( new BoxLayout(replacePanel, BoxLayout.X_AXIS) );
replacePanel.add( replaceLabel );
replacePanel.add( Box.createHorizontalGlue() );
replacePanel.add( Box.createHorizontalStrut( COMPONENT_GAP ) );
replacePanel.add( replaceData );

// Create options panel

JPanel matchPanel = new JPanel();
matchPanel.setLayout( new GridLayout(2, 1) );
matchCase = new JCheckBox( "Match case" );
matchCase.setMnemonic( 'C' );
matchWord = new JCheckBox( "Match word" );
matchWord.setMnemonic( 'W' );
matchPanel.add( matchCase );
matchPanel.add( matchWord );

JPanel searchPanel = new JPanel();
searchPanel.setLayout( new GridLayout(2, 1) );
searchDown = new JRadioButton( "Search Down" );
searchDown.setMnemonic( 'D' );
searchDown.setSelected( true );
searchUp = new JRadioButton( "Search Up" );
searchUp.setMnemonic( 'U' );
searchPanel.add( searchDown );
searchPanel.add( searchUp );

ButtonGroup searchGroup = new ButtonGroup();
searchGroup.add( searchDown );
searchGroup.add( searchUp );

optionPanel = new JPanel();
optionPanel.setLayout( new GridLayout(1, 2) );
optionPanel.setBorder( new TitledBorder( "Options" ) );
optionPanel.add( matchPanel );
optionPanel.add( searchPanel );

// Create command panel

commandPanel = new JPanel();
findNextButton = createButton( commandPanel, "Find Next", 'F' );
replaceButton = createButton( commandPanel, "Replace", 'R' );
replaceAllButton = createButton( commandPanel, "Replace All", 'a' );
closeButton = createButton( commandPanel, "Close", ' ' );
closeButton.setEnabled( true );

// Layout all the panels to build the dialog

JPanel panel = new JPanel();
panel.setLayout( new BoxLayout(panel, BoxLayout.Y_AXIS) );
panel.setBorder( EMPTY_BORDER );
panel.add( findPanel );
panel.add( replacePanel );
panel.add( optionPanel );
panel.add( commandPanel );
setContentPane( panel );

// Set the default button for the dialog

getRootPane().setDefaultButton( findNextButton );

FocusAdapter resetDefaultButton = new FocusAdapter()
{
public void focusLost(FocusEvent e)
{
getRootPane().setDefaultButton( findNextButton );
}
};

//replaceButton.addFocusListener( resetDefaultButton );
//replaceAllButton.addFocusListener( resetDefaultButton );
//closeButton.addFocusListener( resetDefaultButton );

// Enable/Disable buttons on the command panel as find text is entered/deleted

findData.addKeyListener( new KeyAdapter()
{
public void keyReleased(KeyEvent e)
{
// Don't reset search variable when enter is entered
if (e.getKeyCode() != KeyEvent.VK_ENTER)
{
boolean state = ( findData.getDocument().getLength() > 0 );

findNextButton.setEnabled( state );
replaceButton.setEnabled( state );
replaceAllButton.setEnabled( state );

resetSearchVariables();
}
}
});

// Handle escape key

KeyStroke escapeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false);
Action escapeAction = new AbstractAction()
{
public void actionPerformed(ActionEvent e)
{
processClose();

}
};

getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(escapeKeyStroke, "ESCAPE");
getRootPane().getActionMap().put("ESCAPE", escapeAction);

}

public static FindReplace getSharedInstance(Frame owner)
{
if (sharedFindReplace == null)
{
sharedFindReplace = new FindReplace(owner);
sharedFindReplace.setLocationRelativeTo( owner );
}

return sharedFindReplace;
}

public void showFind(JTextComponent textComponent)
{
setTitle( "Find" );
setTextComponent( textComponent );
showReplaceComponents( false );
pack();
setVisible( true );
findData.requestFocus();
resetSearchVariables();
}

public void doFindNext(JTextComponent textComponent)
{
if (findData.getText().length() == 0)
showFind( textComponent );
else
{
setTextComponent( textComponent );
processFindNext();
}
}

public void showReplace(JTextComponent textComponent)
{
setTitle( "Find and Replace" );
setTextComponent( textComponent );
showReplaceComponents( true );
pack();
setVisible( true );
findData.requestFocus();
resetSearchVariables();
}

private void showReplaceComponents(boolean value)
{
replacePanel.setVisible( value );
replaceButton.setVisible( value );
replaceAllButton.setVisible( value );
}

public void actionPerformed(ActionEvent e)
{
Object o = e.getSource();

if ( o == findNextButton )
processFindNext();

if ( o == replaceButton )
processReplace();

if ( o == replaceAllButton )
processReplaceAll();

if ( o == closeButton )
processClose();

}

private JButton createButton(JPanel panel, String label, char mnemonic)
{
JButton button = new JButton( label );
button.setMnemonic( mnemonic );
button.setEnabled( false );
button.addActionListener( this );
panel.add( button );

return button;
}

private boolean processFindNext()
{
// Set variables required for the search

String needle = findData.getText();
String haystack = textComponent.getText();
int offset = textComponent.getSelectionStart();
String selectedText = textComponent.getSelectedText();
textComponent.setSelectionEnd( offset ); // deselect text

// Simplify search when you don't care about case

if ( ! matchCase.isSelected() )
{
haystack = haystack.toLowerCase();
needle = needle.toLowerCase();
}

// When text is already selected,
// change offset so we don't find the same text again

if ( needle.equalsIgnoreCase( selectedText ) )
if ( searchDown() )
offset++;
else
offset--;

// Search for the string and show the result

int result = searchFor( needle, haystack, offset );

if (result == -1)
{
JOptionPane.showMessageDialog(this, "Finished searching the document.", "Find", JOptionPane.INFORMATION_MESSAGE);
resetSearchVariables();
return false;
}
else
{
textComponent.setSelectionStart( result );
textComponent.setSelectionEnd( result + needle.length() );
//textComponent.requestFocus();
return true;
}
}

private boolean searchDown()
{
return searchDown.isSelected();
}

private int searchFor(String needle, String haystack, int offset)
{
int result;
int wrapSearchOffset;

if ( searchDown() )
{
wrapSearchOffset = 0;
result = haystack.indexOf( needle, offset );
}
else
{
wrapSearchOffset = haystack.length();
result = haystack.lastIndexOf( needle, offset );
}

// String not found,
// Attempt to wrap and continue the search

if (result == -1)
if (searchWrap)
{
return result;
}
else
{
searchWrap = true;
return searchFor( needle, haystack, wrapSearchOffset );
}

// String was found,
// Make sure we haven't wrapped and passed the original start position

int wrapResult;

if ( searchDown() )
wrapResult = result - searchStartPosition.getOffset();
else
wrapResult = searchStartPosition.getOffset() - result - 1;

if ( searchWrap && (wrapResult >= 0) )
return -1;

// String was found,
// see if it is a word

if (matchWord.isSelected() && !isWord( haystack, result, needle.length() ) )
if ( searchDown() )
return searchFor( needle, haystack, result+1 );
else
return searchFor( needle, haystack, result-1 );

// The search was successfull

return result;
}

private boolean isWord(String haystack, int offset, int length)
{
int leftSide = offset - 1;
int rightSide = offset + length;

if ( isDelimiter( haystack, leftSide ) && isDelimiter( haystack, rightSide ) )
return true;
else
return false;
}

private boolean isDelimiter(String haystack, int offset)
{
if ( (offset < 0) || (offset > haystack.length()) )
return true;

return ! Character.isLetterOrDigit( haystack.charAt( offset) );
}

private boolean processReplace()
{
String needle = findData.getText();
String replaceText = replaceData.getText();
String selectedText = textComponent.getSelectedText();

if ( matchCase.isSelected() && needle.equals( selectedText ) )
textComponent.replaceSelection( replaceText );

if ( ! matchCase.isSelected() && needle.equalsIgnoreCase( selectedText ) )
textComponent.replaceSelection( replaceText );

return processFindNext();
}

private void processReplaceAll()
{
JViewport viewport = null;
Point point = null;

resetSearchVariables();

Container c = textComponent.getParent();

if (c instanceof JViewport)
{
viewport = (JViewport)c;
point = viewport.getViewPosition();
}

while ( processReplace() );

if (c instanceof JViewport)
{
viewport.setViewPosition( point );
}
}


private void processClose()
{
setVisible( false );
}

private void setTextComponent(JTextComponent textComponent)
{
if (this.textComponent != textComponent)
{
this.textComponent = textComponent;
resetSearchVariables();
}
}

private void resetSearchVariables()
{
try
{
searchWrap = false;
searchStartPosition = textComponent.getDocument().createPosition( textComponent.getSelectionStart() );
}
catch (BadLocationException e)
{
System.out.println( e );
}
}

public static void main(String[] args)
{
// Get the current system Look And Feel

try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) { }

// Populate a text area with test data

//JTextArea text = new JTextArea(20, 40);
JTextPane text = new JTextPane();
Caret selected = new DefaultCaret()
{
public void focusLost(FocusEvent e)
{
setVisible(false);
}
};
selected.setBlinkRate( text.getCaret().getBlinkRate() );
text.setCaret( selected );

try
{
text.read( new FileReader( new File( "FindReplace.java" ) ), "" );
}
catch(IOException e)
{
System.out.println( e );
}
text.getDocument().putProperty( DefaultEditorKit.EndOfLineStringProperty, "\n" );

// Create the top-level container and add contents to it.

JFrame frame = new JFrame();
frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
frame.getContentPane().add( new JScrollPane( text ) );
frame.setSize(400, 400);
frame.setVisible( true );

// display

FindReplace.getSharedInstance( frame ).showReplace( text );
}
}
 
Ranch Hand
Posts: 1535
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're speaking of integrating the FindSearch functionality into the SimpleTextEditor GUI? One way to do it would be with an Action.
In your SimpleTextEditor constructor, add a search action to a JMenu, say File

and somewhere in the body of the (SimpleTextEditor) class add the Action:

It doesn't work as well as it does when run from the main in the FindReplace class.
 
reply
    Bookmark Topic Watch Topic
  • New Topic