Java

Moderators: zibadian
Number of threads: 7818
Number of posts: 18218

This Forum Only
Post New Thread
Single Post View       Linear View       Threaded View      f

Report
help pls..: highlight text in the txt file Posted by saran185 on 2 Feb 2011 at 10:04 PM
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.
 
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
            Action 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 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)
		{
			selectWord.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;

Report
Re: help pls..: highlight text in the txt file Posted by krishbaloda on 2 Feb 2011 at 11:55 PM
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!!
Report
Re: help pls..: highlight text in the txt file Posted by saran185 on 3 Feb 2011 at 3:02 AM
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 ..

Report
Re: help pls..: highlight text in the txt file Posted by krishbaloda on 3 Feb 2011 at 5:43 AM
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.
Report
Re: help pls..: highlight text in the txt file Posted by saran185 on 3 Feb 2011 at 10:09 PM
hi...

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





 

Recent Jobs

Official Programmer's Heaven Blogs
Web Hosting | Browser and Social Games | Gadgets

Popular resources on Programmersheaven.com
Assembly | Basic | C | C# | C++ | Delphi | Flash | Java | JavaScript | Pascal | Perl | PHP | Python | Ruby | Visual Basic
© Copyright 2011 Programmersheaven.com - All rights reserved.
Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Operated by CommunityHeaven, a BootstrapLabs company.