Jump to content

Help with JFileChooser to open a textfile using a menu

- - - - -

  • Please log in to reply
7 replies to this topic

#1
Darkone85

Darkone85

    Learning Programmer

  • Members
  • PipPipPip
  • 30 posts
Hi!

If i have this following class i can open and text file and write its content to the console, but how do i get it to my textArea instead which i have in another class called View??

public class Model extends javax.swing.JFrame {

	@SuppressWarnings("unused")

	private Controller c;

	private String currentFile = null;

	private JFileChooser fc = new JFileChooser();


	public void open() {

		fc = new JFileChooser();


		int value = fc.showOpenDialog(null);

		if(value == JFileChooser.APPROVE_OPTION) {

			File f = fc.getSelectedFile();


			BufferedReader br = null;

			try {

				br = new BufferedReader(new FileReader(f));

			} catch (FileNotFoundException e) {

				e.printStackTrace();

			}

			String st = "";

			try {

				while((st = br.readLine()) != null){

					System.out.print(st);

				}

			} catch (IOException e) {

				e.printStackTrace();

			}

		}

	}


#2
ZekeDragon

ZekeDragon

    Writes binary right handed and hex left handed

  • Moderators
  • 2,103 posts
First, why is your Model class extending JFrame? Second, please edit post away your code if you find a solution, that's kind of annoying and I'm deleting that thread.

I'd imagine that your Model class constructor would need a reference to the View object. Then it would use that reference to the view to call the method that updates the textArea. Something like this:
public class Model

{

    public Model(View someView)

    {

        view = someView;

        // You probably want more in your ctor.

    }


    // Implement everything else over here.


    private View view;

}

Wow I changed my sig!

#3
Darkone85

Darkone85

    Learning Programmer

  • Members
  • PipPipPip
  • 30 posts
thanks for the reply and i have taken away the extend of JFrame for Model and also given the Model() a View as an reference. Sorry for the post eralier, didnt know how to delete old posts.

Still, if i can get the text of the file and printing it out using System.out.print(st)

like this:
String st = "";

			try {

				while((st = br.readLine()) != null){

					System.out.print(st);

				}

			

			}

shouldnt i be able to easily just convert this to my textarea?

if i put for example v.getTextArea().setText(st); either before the System.out.print(st) or after it wont work. If i have it before i will get nothing except an error in the compile, if i have it after i get the first line from the document in the file before it crashes. this is since its a loop and i didnt rly think about it that hard until i put it after and tried.

so since its a loop shouldnt i be able to declare a String which i add every st of to get the whole files text and do something like:
String st = "";

			try {

				while((st = br.readLine()) != null){

                                     [B]   String fileString = ""+st; 

					v.getTextArea().setText(fileString);

					//System.out.print(st);[/B] 

				}

			

			}


#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
  • Yes, that should work, it will only display 1 line tho. But shouldn't cause errors.
  • What's the exception you get?
  • Better give the view a method setText, instead of getting the textArea. The model should know as less as possible about the view.


#5
Darkone85

Darkone85

    Learning Programmer

  • Members
  • PipPipPip
  • 30 posts

wim DC said:

  • Yes, that should work, it will only display 1 line tho. But shouldn't cause errors.
  • What's the exception you get?
  • Better give the view a method setText, instead of getting the textArea. The model should know as less as possible about the view.

Thanks for helping... still dont get this tho. Ill paste MVC-classes and try to explain.

I have similarly "almost" solved the save()-to-file function. I can write to selected file whatever i put into " "; but I cant use v.getTextArea().setText() as an reference instead of it to actually write whats in my textarea to the file. Maybe this is having to do with that i am getting the textarea as u said. But i already created getters and setter so i can call it from Controller too, how would i change for the best?

UPDATE Wow, i found out that i have two Constructors in Model, one which i havent noticed, must have accidently added it sometime. Thing is when i remove it which is completely blank the constructors in View and Controller are affected and vice versa. If i remove the one "i thought i was using" and letting the blank be left its still the same. Can you explain whats happening?

I bold out all the essential parts. What is the best to do here?

Also, the exception that happens if i dont use System.out.print(st) or System.out.print("Whatever I like but not area content") is a nullpointerexception that traces back to the lines where i either if so tries to write: v.getTextArea.setText()

VIEW
import java.awt.*;


@SuppressWarnings("serial")

public class View extends javax.swing.JFrame {

	// Variables declaration

	private Controller c;

	private Model m;

	

    private javax.swing.JMenuItem copy;

    private javax.swing.JMenuItem cut;

    private javax.swing.JMenu edit;

    private javax.swing.JMenuItem exit;

    private javax.swing.JMenu file;

    private javax.swing.JMenuBar menuBar;

    private javax.swing.JMenuItem newFile;

    private javax.swing.JMenuItem open;

    private javax.swing.JMenuItem paste;

    private javax.swing.JMenuItem save;

    private javax.swing.JMenuItem saveAs;

    private javax.swing.JScrollPane scrollPane;

	private javax.swing.JTextArea textArea;

    // End of variables declaration


    /** Creates new form View */

    [B]public View(Controller con) {

        c = con;

        m = new Model();[/B]

    	initComponents();

    }


    /** This method is called from within the constructor to

     * initialize the form.

     */

    private void initComponents() {

    	

    	scrollPane = new javax.swing.JScrollPane();

        setTextArea(new javax.swing.JTextArea());

        menuBar = new javax.swing.JMenuBar();

        setFile(new javax.swing.JMenu());

        newFile = new javax.swing.JMenuItem();

        open = new javax.swing.JMenuItem();

        save = new javax.swing.JMenuItem();

        saveAs = new javax.swing.JMenuItem();

        exit = new javax.swing.JMenuItem();

        edit = new javax.swing.JMenu();

        copy = new javax.swing.JMenuItem();

        cut = new javax.swing.JMenuItem();

        paste = new javax.swing.JMenuItem();


        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        setTitle("Notepad");

        

        getTextArea().setColumns(28);

        getTextArea().setRows(22);

       

        scrollPane.setViewportView(getTextArea());

        this.add(scrollPane, BorderLayout.CENTER);


        getFile().setText("File");


        newFile.setMnemonic('N');

        newFile.setText("New");

        newFile.addActionListener(new NewFileListener(this));

        getFile().add(newFile);


        open.setMnemonic('O');

        open.setText("Open");

        open.setActionCommand("Open");

        open.addActionListener(new OpenListener(this));

        getFile().add(open);


        save.setMnemonic('S');

        save.setText("Save");

        getFile().add(save);


        saveAs.setMnemonic('A');

        saveAs.setText("Save As...");

        getFile().add(saveAs);


        exit.setMnemonic('E');

        exit.setText("Exit");

        exit.addActionListener(new ExitListener(this));

        getFile().add(exit);


        menuBar.add(getFile());


        edit.setText("Edit");


        copy.setMnemonic('C');

        copy.setText("Copy");

        edit.add(copy);


        cut.setMnemonic('U');

        cut.setText("Cut");

        edit.add(cut);


        paste.setMnemonic('P');

        paste.setText("Paste");

        edit.add(paste);


        menuBar.add(edit);


        setJMenuBar(menuBar);

        

        // Set the application in the middle of the screen

        int width = 350;

        int height = 500;

        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();

        int x = (screen.width - width) / 2;

        int y = (screen.height - height) / 2;

        setBounds(x, y, width, height);

        

        this.pack();

        this.setVisible(true);

    }

    

    public void handleNewFile() {

    	m.newFile();

    }

    

	public void handleOpen() {

		m.open();

	}

	

	public void handleSave() {

		m.save();

	}

    

	public void handleSaveAs() {

		m.saveAs();

	}

	

	public void handleExit() {

		c.exit();

	}


	[B]public void setTextArea(javax.swing.JTextArea textArea) {

		this.textArea = textArea;

	}


	public javax.swing.JTextArea getTextArea() {

		return textArea;

	}[/B]


	public void setFile(javax.swing.JMenu file) {

		this.file = file;

	}


	public javax.swing.JMenu getFile() {

		return file;

	}

	

}


MODEL
import java.io.*;

import javax.swing.JFileChooser;


public class Model {

	@SuppressWarnings("unused")

	private Controller c;

	@SuppressWarnings("unused")

	private View v;

	private String currentFile = null;

	private JFileChooser fc = new JFileChooser();


	[B]public Model(View vi) {

		c = new Controller();

		v = vi;

	}[/B]


	public void open() {


		fc = new JFileChooser();

		fc.setDialogTitle("Open File");


		int value = fc.showOpenDialog(null);

		if(value == JFileChooser.APPROVE_OPTION) {

			File f = fc.getSelectedFile();


			BufferedReader br = null;

			try {

				br = new BufferedReader(new FileReader(f));


			} catch (FileNotFoundException e) {

				e.printStackTrace();

			}

			String st = "";

			try {

				while((st = br.readLine()) != null){

					//String fileString = st;

					//v.getTextArea().setText(fileString);

					[B]System.out.print(st);[/B]

				}


			} catch (IOException e) {

				e.printStackTrace();

			}

		}

	}



	public void save() {


	}


	public void saveAs() {

		fc = new JFileChooser();

		int value = fc.showSaveDialog(null);

		if(value == JFileChooser.APPROVE_OPTION) {

			File f = fc.getSelectedFile().getAbsoluteFile();

			try {

				FileWriter fw = new FileWriter(f);

				BufferedWriter out = new BufferedWriter(fw);

				[B]out.write("Whatever I want to file inside these but not my textarea");[/B]

				//Close the output stream

				out.close();

			}catch (Exception e)

			{ //Catch exception if any

				System.err.println("Error: " + e.getMessage());

			}

		}

	}

	public void saveCurrentFile() {


	}


	[B]public Model() {

                  //WTF?

	}[/B]


	public void newFile() {


	}


	public void setCurrentFile(String currentFile) {

		this.currentFile = currentFile;

	}


	public String getCurrentFile() {

		return currentFile;

	}



}



import javax.swing.JOptionPane;


	@SuppressWarnings("serial")

public class Controller {

	private View v;

	private Model m;

	private String name = null;

	private int option;


	[B]public Controller() {

		v = new View(this);

		m = new Model();

	}[/B]

	

	public void exit() {

			// if the output area is empty just quit, otherwise prompt before leaving

			  if (!v.getTextArea().getText().equals("") && !v.getTextArea().getText().equals(m.getCurrentFile()))

			  {	

				  	if(name == null)

		            /* Shows a Confirm dialog box. */

		            option = JOptionPane.showConfirmDialog(null,"Do you want to save the file?");

		            if(option == 0)

		            {

		               /* Calls the saveAs() method. */

		               m.saveAs();

		               /* Closes the main application. */

		               System.exit(0);

		            }

		            if(option == 1)

		            {

		               System.exit(0);

		            }

		         

		         else

		         {

		            /* Shows a Confirm dialog box. */

		            option = JOptionPane.showConfirmDialog(null,"Do you want to save the file?");

		            if(option == 0)

		            {

		               /* Calls the save() method. */

		               m.save();

		               System.exit(0);

		            }

		            if(option == 1)

		            {

		               System.exit(0);

		            }

		         }

		      }

		      else

		      {

		          System.exit(0);

		      }

		   }

	

	

	public static void main(String args[]) {

		@SuppressWarnings("unused")

		Controller c = new Controller();

 	}

}


#6
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
The perfect situation, in my opinion, would be if the model has no reference to the view or controller. Controller will ask the model stuff (call methods) and the model can return stuff. But the model won't do "controller.something()" or "view.something()"

Then you got the view, it also has no reference to the controller either. But the xListeners will have. (So maybe you pass the controller to the view, but only to pass it on to the xListeners, not to actually go call methods at controller)
The end result would look like:

View --> xListener --> Controller  --> Model

  |                       |

  +--<---<---<---<---<----+
Note that even though the arrow between controller and model points towards model, that doesn't mean that model can't return stuff, like in getters. It just means that only controller will call model, and not the other way around.


example controller class:

public class Controller{

    private View view;

    private Model model;

 

   ....

}


Example xListener:

public buttonListener implements ActionListener{

    private Controller controller;


    ....


}


And model and view are purely model and view, no relations at their sides to the controller.


Now, what's certainly wrong in your code is that in the model's contstructor you create a new controller, while it should get the one that allready exists.

#7
Darkone85

Darkone85

    Learning Programmer

  • Members
  • PipPipPip
  • 30 posts
thx... but im not reaching any solutions. i tried to backup my files and completely turn around on the mvc-connections due to what you said but i did not get it to work.

now my listeners look like this:
import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;


public class SaveAsListener implements ActionListener {

	private View v;

	

	public SaveAsListener(View view) {

		v = view;

	}


	public void actionPerformed(ActionEvent e) {

		v.handleSaveAs();

	}

}

but as it works with getting input from an file and writing to a file i guess its okay. the main thing is how i do to actually write to file whats already in my textarea and vice versa, to read from file to my textarea??? as said before i can get the content of the test.txt either by out.write in this method:
public void saveAs() {

		fc = new JFileChooser();

		int value = fc.showSaveDialog(null);

		if(value == JFileChooser.APPROVE_OPTION) {

			File f = fc.getSelectedFile().getAbsoluteFile();

			String textToFile = "";

			try {

				FileWriter fw = new FileWriter(f);

				BufferedWriter out = new BufferedWriter(fw);

				[SIZE="4"]out.write("HEJ"); // WRITES HEJ TO TEST.TXT[/SIZE]

				textToFile += fw;

				//Close the output stream

				out.close();

			}catch (Exception e)

			{ //Catch exception if any

				System.err.println("Error: " + e.getMessage());

			}

		}

	}
and i can also read that same file using System.out.print in this method:
public void open() {


		fc = new JFileChooser();

		fc.setDialogTitle("Open File");


		int value = fc.showOpenDialog(null);

		if(value == JFileChooser.APPROVE_OPTION) {

			File f = fc.getSelectedFile();


			BufferedReader br = null;

			try {

				br = new BufferedReader(new FileReader(f));


			} catch (FileNotFoundException e) {

				System.err.println("Error: " + e.getMessage());

				e.printStackTrace();

			}

			String textFileText = "";

			String st = "";

			try {

				while((st = br.readLine()) != null){

					textFileText += st;

					[SIZE="4"]System.out.print(st); //READS ONE ROW FROM TEST.TXT [/SIZE]

				}


			} catch (IOException e) {

				System.err.println("Error: " + e.getMessage());

				e.printStackTrace();

			}

		}

	}



although i tried everythingt i cant "convert" what i already got til my textarea. the v.getTextArea().getText(); has no compile errors but returns null as an exception.

aaaaaaanyone? im blind.

#8
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
In view class:

public String getText(){

    return textArea.getText();

}


public void setText(String text){

    textArea.setText(text);

}



public void addNewLine(String text){

    textArea.setText( textArea.getText() + "\n" + text );

}


saveAs:

        File f = fc.getSelectedFile().getAbsoluteFile();

	String textToFile = getText();

        textToFile = textToFile.replaceAll("\n", "\r\n"); //Otherwise it won't show newlines in notepad


	try {

		FileWriter fw = new FileWriter(f);

		BufferedWriter out = new BufferedWriter(fw);

		out.write(textToFile);

		out.close();

	}catch (Exception e){

		System.err.println("Error: " + e.getMessage());

	}


Open:

setText(""); //clear textArea

while((st = br.readLine()) != null)

	 addNewLine(st);

}


Or something like that.




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users