Go Back   CodingForums.com > :: Server side development > Java and JSP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-21-2011, 11:23 PM   PM User | #1
itgeek25
New to the CF scene

 
Join Date: Nov 2011
Posts: 9
Thanks: 1
Thanked 1 Time in 1 Post
itgeek25 is an unknown quantity at this point
Please Help with FileDialog and Loading a File

I have two class files in a Java package. One is for the actual program, Padtest.java and the other is for loading a document, OpenBox.java. I have the them both working fine. The issue I am having is to get the output of the load file inputted to the textarea of the main file. I have recreated and tested on another project with the SAME syntax, just different class names, and it works. ??????????
I have been looking and looking and it may just be something simple. Any help would be appreciated. Thanks in advance.

BTW, I am new to Java and I am teaching myself. This program is justa simple notepad look-a-like.

Here is the main program:
Code:
package notePad;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import java.io.IOException;
import java.io.InputStreamReader;

import javax.swing.*;

public class Padtest extends JFrame {
	
	JTextArea textarea = new JTextArea(5 ,30);
	
	JMenu file = new JMenu("File");
	JMenu edit = new JMenu("Edit");
	JMenu format = new JMenu("Format");
	JMenu view = new JMenu("View");
	JMenu help = new JMenu("Help");
	JMenuItem new1 = new JMenuItem("New             Ctrl + N");
	JMenuItem open = new JMenuItem("Open            Ctrl + O");
	JMenuItem save = new JMenuItem("Save            Ctrl + S");
	JMenuItem save1 = new JMenuItem("Save As...             ");
	JMenuItem exit = new JMenuItem("Exit                    ");
	JMenuBar menubar = new JMenuBar();
	
	event1 ex = new event1();
	event2 op = new event2();
	event3 sva = new event3();
	

	public Padtest() {
		super("Notepad");
		setSize(400, 400);
		
		setJMenuBar(menubar);
		menubar.add(file);
		menubar.add(edit);
		menubar.add(format);
		menubar.add(view);
		menubar.add(help);
		file.add(new1);
		
		//add textarea
		add(textarea);
		
		//create list item in file and add event handler to it
		file.add(open);
		open.addActionListener(op);
		
		//create save function
		file.add(save);
		
		//create save as event handler
		file.add(save1);
		save1.addActionListener(sva);
		
		//create list item in file and add event handler to it
		file.add(exit);
		exit.addActionListener(ex);
	
		//adds a scroll bar to textarea
		JScrollPane scrollPane = new JScrollPane(textarea);
		setPreferredSize(new Dimension(450, 110));
		add(scrollPane, BorderLayout.CENTER);
	}

	public void insert(String s, int i) {
		textarea.insert( s, 1);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Padtest padtest = new Padtest();
		padtest.setVisible(true);
		
		try { 
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"); 
        } catch (Exception ex) { 
            ex.printStackTrace(); 
        }
		padtest.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}
	


public class event1 implements ActionListener {  
	
		
		public void actionPerformed(ActionEvent ex) { 
			System.exit(0);
		}
	}

public class event3 implements ActionListener {  
	
	
	public void actionPerformed(ActionEvent sva) { 
		SaveAsDialog sad = new SaveAsDialog();
		
	}
}

public class event2 implements ActionListener {  
	
	
	public void actionPerformed(ActionEvent op) { 
			try {
				OpenBox ope = new OpenBox();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

    	}
	}

public void setText(String s) {
	// TODO Auto-generated method stub
	textarea.setText(s);
}
}
And here is the Loading program:
Code:
package notePad;

import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.text.StringContent;

public class OpenBox extends JFrame {

	public OpenBox() throws IOException {
		
		super();
		
		Padtest textarea = new Padtest();
		
		Frame frame = null;
		FileDialog chooser;
		String homedir;
		homedir = System.getProperty("user.home");
		chooser= new FileDialog( frame );
		chooser.setLocationRelativeTo( null );
		chooser.setLocation( 200, 200 );
		chooser.setDirectory(homedir);
		chooser.setVisible( true );
		
		String filename = chooser.getFile();
		String directory = chooser.getDirectory();
		String file = directory + filename;
		
		int i=0;
		
		FileReader into = null;
		try {
		     into = new FileReader(file); // And a char stream to read it
		      char[] buffer = new char[4096]; // Read 4K characters at a time
		      int len; // How many chars read each time
		while ((len = into.read(buffer)) != -1)
		{ 
			String s = new String(buffer, 0, len);
			textarea.insert( s, 1 );
		i++;
			System.out.println(s);
		}
		}
		catch(IOException e) {
			System.out.println("Error");
			return;
		}	

			}
	/**
	 * @param args
	 * @param br 
	 * @param strLine 
	 * @param 
	 * @param 
	 * @throws IOException 
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
	}
}

Last edited by Fou-Lu; 11-22-2011 at 02:37 PM.. Reason: Added / tags
itgeek25 is offline   Reply With Quote
Old 11-22-2011, 02:55 PM   PM User | #2
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
First up is your insert method. You are just overwritting the first char over and over again. That should be writing to the textarea's 'i' position, not 1. The handling needs to work from the end of the total, but that can easily be retrieved from the textarea.getText().length(). Be warned that will throw a NullPointerException if there's no text at all. I'd actually recommend you use the .append() method instead, which will neither throw an exception nor does it require an offset.

I'd actually drop the use of the FileDialog completely. Since the other work is in swing, you should use the JFileChooser instead (its a little strange to have 1 component in awt while the other's are all swing). The rest of the work is similar to what you have done, its just the chooser that changes.
Fou-Lu is offline   Reply With Quote
Old 11-22-2011, 11:52 PM   PM User | #3
itgeek25
New to the CF scene

 
Join Date: Nov 2011
Posts: 9
Thanks: 1
Thanked 1 Time in 1 Post
itgeek25 is an unknown quantity at this point
I have used JFileChooser

I have used JFileChooser with just about the same syntax. That was easy enough for me to use and get it to work. Not much trial and error tests. But I would like to use FileDialog becuase it resembled the specific OS that the user users. In my case the Windows 7 open file dialog. THe GUI just looks better.

I also have tried the append instead of insert and no luck.

I also tried changing the location of the inserted text, like you have suggested with the i int. Still no luck.

Any more ideas. Thanks again. This is just driving me crazy.
itgeek25 is offline   Reply With Quote
Old 11-23-2011, 12:42 AM   PM User | #4
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,752
Thanks: 4
Thanked 2,468 Times in 2,437 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
Quote:
Originally Posted by itgeek25 View Post
I have used JFileChooser with just about the same syntax. That was easy enough for me to use and get it to work. Not much trial and error tests. But I would like to use FileDialog becuase it resembled the specific OS that the user users. In my case the Windows 7 open file dialog. THe GUI just looks better.

I also have tried the append instead of insert and no luck.

I also tried changing the location of the inserted text, like you have suggested with the i int. Still no luck.

Any more ideas. Thanks again. This is just driving me crazy.
Try to repaint after you've dealt with the fields.
As for the look, use the system L&F instead of nimbus. Here's a quick example:
PHP Code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;

import javax.swing.*;

public class 
FilechooserTest extends JFrame
{
    public 
JTextArea jtaText;
    
    public 
FilechooserTest()
    {
        try
        {
            
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (
Exception ex)
        {
            
System.out.println("Unable to set UI: " ex.getMessage());
        }
        
        
JMenuBar jmb = new JMenuBar();
        
JMenu jmF = new JMenu("File");
        
JMenuItem jmiOpen = new JMenuItem("Open");
        
JMenuItem jmiClose = new JMenuItem("Close");
        
        
jtaText = new JTextArea();
        
jtaText.setSize(450450);
        
JScrollPane jsp = new JScrollPane(jtaText);
        
        
jmF.add(jmiOpen);
        
jmF.add(jmiClose);
        
jmb.add(jmF);

        
this.setJMenuBar(jmb);
        
this.setSize(500500);
        
this.getContentPane().add(jspBorderLayout.CENTER);
        
this.setVisible(true);
        
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        
// Lets add a couple of events then
        // We'll cheat with a couple of Anonymous listeners.
        
final FilechooserTest sThis this;
        
jmiOpen.addActionListener(new ActionListener(){
            @
Override
            
public void actionPerformed(ActionEvent e)
            {
                
JFileChooser jfc = new JFileChooser();
                
int iOpen jfc.showOpenDialog(sThis);
                switch (
iOpen)
                {
                    case 
JFileChooser.APPROVE_OPTION:
                        
File f jfc.getSelectedFile();
                        if (
f.isFile() && f.canRead())
                        {
                            try
                            {
                                
FileReader reader = new FileReader(f);
                                
char[] cBuffer = new char[10];
                                while(-
!= reader.read(cBuffer))
                                {
                                    
sThis.jtaText.append(new String(cBuffer));
                                }
                            }
                            catch (
IOException re)
                            {
                                
re.printStackTrace();
                            }
                        }
                        break;
                }
                
repaint();
            }            
        });
        
        
jmiClose.addActionListener(new ActionListener(){
            public 
void actionPerformed(ActionEvent e)
            {
                
sThis.dispose();
            }
            
        });
    }
    
    public static 
void main(String... argv)
    {
        
javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public 
void run() {
                new 
FilechooserTest();
            }
        });
    }

You should find that the file chooser works a lot easier.
Fou-Lu is offline   Reply With Quote
Old 11-23-2011, 12:51 AM   PM User | #5
itgeek25
New to the CF scene

 
Join Date: Nov 2011
Posts: 9
Thanks: 1
Thanked 1 Time in 1 Post
itgeek25 is an unknown quantity at this point
Answer

Wow, this was making me pull my hair out but I found the answer. I referenced in the public main the public class as:
Code:
padtest.setVisible(true);
I had to delete this and add this to the public class:
Code:
setVisible(true);
Thanks guys for your help.
itgeek25 is offline   Reply With Quote
Reply

Bookmarks

Tags
filedialog, filereader, loadfile, text

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 02:19 AM.


Advertisement
Log in to turn off these ads.