Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Sign In with Facebook Sign In with Google Sign In with OpenID

Categories

We have migrated to a new platform! Please note that you will need to reset your password to log in (your credentials are still in-tact though). Please contact lee@programmersheaven.com if you have questions.
Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

help pls..: highlight text in the txt file

saran185saran185 Posts: 23Member
hi ...
i ve written a code that would highlight a word in text file when i keep my cursor on that word. I ve another code that uses a file chooser to select a text file and open it in the text area. now i want to integrate both the code. i.e.. I need to choose a txt file from the system and open it the text area. Then when i mouse click on any word in that text file ( that is opened in the text area)that word should get highlighted..

below is my code. i get some errors wherever the word "action " is mentioned..is nay line missing or if anything is to be imported?? Im not sure what is to be included..Im running java code using netbeans ide..The orange parts of the code are the errors..
So pls help me in fixing the errors. [code]
package jfilechooserdemo.resources;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFileChooser;
import java.util.Scanner;
import java.awt.*;
import java.awt.event.*;
import javax.swing.text.*;

class MyCustomFilter extends javax.swing.filechooser.FileFilter {
@Override
public boolean accept(File file) {
// Allow only directories, or files with ".txt" extension
return file.isDirectory() || file.getAbsolutePath().endsWith(".txt");
}
@Override
public String getDescription() {
// This description will be displayed in the dialog,
// hard-coded = ugly, should be done via I18N
return "Text documents (*.txt)";
}
}

public class JFileChooserDemo extends javax.swing.JFrame implements MouseListener {

/** Creates new form JFileChooserDemo */

public JFileChooserDemo() {
initComponents();

}
private void OpenActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
int returnVal = fileChooser.showOpenDialog(this);
String filePath;

if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
filePath = file.getAbsolutePath();
try {
// What to do with the file, e.g. display it in a TextArea
[color=Orange]Action[/color] selectWord;
textarea.read( new FileReader( file.getAbsolutePath() ), null );
textarea.addMouseListener( this );

String s=new String();
selectWord = getAction(DefaultEditorKit.selectWordAction);
countLetter(filePath);

} catch (IOException ex) {
System.out.println("problem accessing file"+file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}

private void ExitActionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0); // TODO add your handling code here:
}

private void countLetter(String filePath){
Scanner in = null;
try{
in = new Scanner(new File(filePath));
}catch(Exception e){
System.out.print("Not got");
}
int nbWords = 0;

while(in.hasNext()) {
String a = in.next();

nbWords++;
}
String ss = ""+nbWords;
jLabel4.setText("the number of words are: "+ss);
System.out.println(nbWords);


}
private [color=Orange]Action[/color] getAction(String name)
{
[color=Orange]Actio[/color]n action = null;
[color=Orange]Action[[/color]] actions = textarea.getActions();

for (int i = 0; i < actions.length; i++)
{
if (name.equals( actions[i].getValue([color=Orange]Action[/color].NAME).toString() ) )
{
action = actions[i];
break;
}
}

return [color=Orange]action[/color];
}
public void mouseClicked(MouseEvent e)
{

if ( [color=Orange]SwingUtilities[/color].isLeftMouseButton(e) && e.getClickCount() == 1)
{
[color=Orange]selectWord.[/color]actionPerformed( null );



}
}

public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
private void wordcountActionPerformed(java.awt.event.ActionEvent evt) {

}

/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new JFileChooserDemo().setVisible(true);
}
});
}

// Variables declaration - do not modify
private javax.swing.JMenuItem Exit;
private javax.swing.JMenuItem Open;
private javax.swing.JFileChooser fileChooser;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPopupMenu jPopupMenu1;
private javax.swing.JPopupMenu jPopupMenu2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextPane jTextPane1;
private javax.swing.JTextPane jTextPane2;
private javax.swing.JTextArea textarea;
private javax.swing.JMenu wordcount;[/code]

Comments

  • krishbalodakrishbaloda Posts: 45Member
    Hey saran185,

    u really don't need things like that u just add a button in ur jframe. and then call a function having File chooser code and pass the absolute path to ur file variable. that will open the file in frame.

    Good luck!!
  • saran185saran185 Posts: 23Member
    hi...
    can u be more clear of what should be modified....im not able to understand your point..
    sry..n thanks..
    Should the filechooser func be called somewhere else..?? im not clear ..

  • krishbalodakrishbaloda Posts: 45Member
    import java.awt.Color;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    import java.io.BufferedReader;
    import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStreamReader;
    import javax.swing.Action;
    import javax.swing.JButton;
    import javax.swing.JFileChooser;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JOptionPane;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    import javax.swing.SwingUtilities;
    import javax.swing.event.AncestorListener;
    import javax.swing.filechooser.FileFilter;
    import javax.swing.text.DefaultEditorKit;

    public class CustomerNew implements MouseListener{
    JFrame frm;
    JPanel jp;
    JTextArea textArea;
    Action selectLine;
    private FileFilter fJavaFilter;
    private File fFile;
    String strLine;
    public CustomerNew() {
    textArea= new JTextArea();
    frm = new JFrame();
    frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) ;
    frm.setSize(1000, 735);
    frm.setVisible(true);
    JMenuItem fMenuOpen = null;
    JMenu m = new JMenu("File");
    m.add(fMenuOpen = makeMenuItem("Open"));
    JMenuBar mb = new JMenuBar();
    mb.add(m);
    frm.setJMenuBar(mb);
    jp = new JPanel();
    jp.setBounds(10, 280, 110, 270);
    textArea.setBounds(50,50,150,150);
    frm.add(textArea);
    frm.add(jp);
    selectLine =getAction(DefaultEditorKit.selectWordAction);
    textArea.addMouseListener(this);
    }
    public static void main(String[] args) {
    CustomerNew a= new CustomerNew();
    }
    private Action getAction(String name)
    {
    Action action = null;
    Action[] actions = textArea.getActions();
    for (int i = 0; i < actions.length; i++)
    {
    if (name.equals( actions[i].getValue(Action.NAME).toString() ) )
    {
    action = actions[i];
    break;
    }
    }
    return action;
    }
    public void mouseClicked(MouseEvent e)
    {
    if ( SwingUtilities.isLeftMouseButton(e) && e.getClickCount() == 1)
    {
    selectLine.actionPerformed( null );
    }
    }
    public void mousePressed(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    private JMenuItem makeMenuItem(String name) {
    JMenuItem m = new JMenuItem(name);
    m.addActionListener(new filemenu());
    return m;}
    class filemenu implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    boolean status = false;
    String command = e.getActionCommand();
    if (command.equals("Open")) {
    status = openFile();
    if (!status)
    JOptionPane.showMessageDialog(null, "Error opening file!",
    "File Open Error", JOptionPane.ERROR_MESSAGE);
    }
    }// actionPerformed end
    }// class end filemenu
    boolean openFile() {
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Open File");
    // Choose only files, not directories
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    // Start in current directory
    fc.setCurrentDirectory(new File("."));
    // Set filter for Java source files.
    fc.setFileFilter(fJavaFilter);
    // Now open chooser
    int result = fc.showOpenDialog(frm);
    if (result == JFileChooser.CANCEL_OPTION) {
    return true;
    }
    else if (result == JFileChooser.APPROVE_OPTION) {
    fFile = fc.getSelectedFile();
    try {
    FileInputStream fstream = new FileInputStream(fFile);
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
    BufferedReader br = new BufferedReader(
    new InputStreamReader(in));
    // Read File Line By Line
    strLine = br.readLine();
    // Print the content on the console
    // System.out.println (strLine);
    textArea.setText(strLine);
    System.out.println("integer conversion done& value r in int");
    // filethread ft=new filethread(fr);
    }// try end
    catch (Exception e) {// Catch exception if any
    System.err.println("Error: xyz" + e.getMessage());
    }
    System.out.println("end of open file");
    }// elseif approve option
    else {
    return false;
    }
    return true;
    } // openFile
    }

    change the class name accordingly. i think this is what u need.
  • saran185saran185 Posts: 23Member
    hi...

    thanks for helping me .. The code u gave was the one i expected..it was very helpful..thanks..:-)


Sign In or Register to comment.