Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 7 of 7

Thread: Make my code follow MVC

  1. #1
    Junior Member
    Join Date
    Apr 2010
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Make my code follow MVC

    I want to have my program in three classes according to the MCV-model. The problem is that I cannot manage to do it right, cause it won't start and other things. This is the code when it is NOT in MVC:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.Random;
     
    public class Class1 extends JFrame
           implements ActionListener {
     
      private JMenuItem fMenuOpen;
      private JMenuItem fMenuSave;
      private JMenuItem fMenuClose;
      private JMenuItem fMenuRandom;
      private JMenuItem fMenuClear;
      private JTextArea textruta; 
      File theFile = new File ("*.java");
     
      public Class1 (String title) {
        super(title);
     
        Container content_pane = getContentPane();
     
        content_pane.setLayout (new BorderLayout());
        textruta = new JTextArea();
     
        JMenu downMenu = new JMenu ("Arkiv");
        content_pane.add(textruta);
     
        downMenu.add(fMenuRandom = createMenuItem("Random numbers"));
        downMenu.add(fMenuClear = createMenuItem("Clear"));
        downMenu.add(fMenuSave  = createMenuItem("Save"));
        downMenu.add(fMenuOpen  = createMenuItem("Open"));
        downMenu.addSeparator();
        downMenu.add(fMenuClose = createMenuItem("Quit"));
     
        JMenuBar menuBar = new JMenuBar();
        menuBar.add (downMenu);
     
        setJMenuBar (menuBar);
        setSize (250, 250);
        setLocation(400, 100);
      } 
     
    	private JMenuItem createMenuItem(String name) {
    		JMenuItem m = new JMenuItem(name);
    		m.addActionListener(this);
    		return m;
    	}
     
      public void actionPerformed (ActionEvent e) {
        boolean status = false;
     
        String command = e.getActionCommand();
        if (command.equals("Clear")){
        	textruta.setText(null);
        }
     
        if (command.equals("Random numbers")){
     
        	Random randomNr = new Random();
     
             int tal;
             for (int i = 0; i < 7; i++) {
                 tal = randomNr.nextInt(35);
                 textruta.append(tal + " ");
             }
        }
     
        if  (command.equals ("Open")) {
        status = openFile ();
     
        } else if (command.equals ("Save")) {
            status = saveFile ();
     
        } else if (command.equals ("Quit") ) {
            System.exit(1);
        }
      } 
     
      boolean openFile () {
     
          JFileChooser fc = new JFileChooser();
          fc.setDialogTitle ("Open file");
     
          int result = fc.showOpenDialog(this);
     
          if (result == JFileChooser.CANCEL_OPTION) {
              return true;
          } else if (result == JFileChooser.APPROVE_OPTION) {
     
        	  theFile = fc.getSelectedFile();
              String file_string = readFile (theFile);
     
              if (file_string != null)
            	  textruta.setText (file_string);
              else
                  return false;
          } 
          return true;
       } 
     
       boolean saveFile() {
         File file = null;
         JFileChooser fc = new JFileChooser();
     
         fc.setSelectedFile (theFile);
     
         int result = fc.showSaveDialog (this);
     
         if (result == JFileChooser.CANCEL_OPTION) {
             return true;
         } else if (result == JFileChooser.APPROVE_OPTION) {
        	 theFile = fc.getSelectedFile();
     
             return writeFile (theFile, textruta.getText());
         } else {
           return false;
         }
      } 
     
      public String readFile (File file) {
     
        StringBuffer fileBuffer;
        String fileString = null;
        String line;
     
        try {
          FileReader in = new FileReader (file);
          BufferedReader dis = new BufferedReader(in);
          fileBuffer = new StringBuffer() ;
     
          while ((line = dis.readLine()) != null) {
                fileBuffer.append(line + "\n");
          }
     
          in.close();
          fileString = fileBuffer.toString();
        }
        catch(IOException e) {
          return null;
        }
        return fileString;
      } 
     
      public static boolean writeFile(File file, String dataString) {
        try {
           PrintWriter out =
             new PrintWriter(new BufferedWriter (new FileWriter (file)));
           out.print(dataString);
           out.flush();
           out.close();
        }
        catch (IOException e) {
           return false;
        }
        return true;
      } 
     
      public static void main(String [] args) {
        String title = "Lotto";
        Class1 f = new Class1 (title);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
      }
    }
    Last edited by helloworld922; November 23rd, 2010 at 10:46 AM.


  2. #2
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Make my code follow MVC

    Please put your code in highlight tags so everyone can read it. It is very difficult to read and understand your code when it is just posted without any tags. See my signature for information how to tag.

    Also, please provide more information as to what is happening and what you are wanting to happen.
    Can you explain what MCV-model is, I am unsure and most people on forums will not bother to do a google search in order to help you?
    cause it won't start and other things.
    What exactly won't start and what other things are happening that shouldn't or not happening that should. Most people on the forum will not help you if you do not provide enough information about what is happening and what you are wanting.


    I'll help you when I have more information about what you are trying to accomplish. It also doesn't hurt to take what I said to heart next time so you receive faster and better help. We get a lot of people asking for help on the forum, and most of the helpers will simply look at a post and decide if it is not worth their time if it doesn't look right, if too much unnecessary code is posted, or if no explanation was given for the problem and solution.
    Last edited by aussiemcgr; November 22nd, 2010 at 09:23 AM.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  3. #3
    Junior Member
    Join Date
    Apr 2010
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Make my code follow MVC

    I want this code to be in the MVC-model. MVC stands for Model-View-Control. You should have the graphics for the program in the view-class, and the code for doing operations in the control-class. The model-class is the class that starts the program, I think.

    So, the graphic, the listener and the logic in seperate files. All attributes should be private and only methods that has to be public should be that. As much as possible should be private.

    As my code is now, it is working, but when I try to seperate parts of the code into other classes, I do not really know how to do and change the code.

    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.Random;
     
    public class Class1 extends JFrame
    implements ActionListener {
     
    private JMenuItem fMenuOpen;
    private JMenuItem fMenuSave;
    private JMenuItem fMenuClose;
    private JMenuItem fMenuRandom;
    private JMenuItem fMenuClear;
    private JTextArea textruta;
    File theFile = new File ("*.java");
     
    public Class1 (String title) {
    super(title);
     
    Container content_pane = getContentPane();
     
    content_pane.setLayout (new BorderLayout());
    textruta = new JTextArea();
     
    JMenu downMenu = new JMenu ("Arkiv");
    content_pane.add(textruta);
     
    downMenu.add(fMenuRandom = createMenuItem("Random numbers"));
    downMenu.add(fMenuClear = createMenuItem("Clear"));
    downMenu.add(fMenuSave = createMenuItem("Save"));
    downMenu.add(fMenuOpen = createMenuItem("Open"));
    downMenu.addSeparator();
    downMenu.add(fMenuClose = createMenuItem("Quit"));
     
    JMenuBar menuBar = new JMenuBar();
    menuBar.add (downMenu);
     
    setJMenuBar (menuBar);
    setSize (250, 250);
    setLocation(400, 100);
    }
     
    private JMenuItem createMenuItem(String name) {
    JMenuItem m = new JMenuItem(name);
    m.addActionListener(this);
    return m;
    }
     
    public void actionPerformed (ActionEvent e) {
    boolean status = false;
     
    String command = e.getActionCommand();
    if (command.equals("Clear")){
    textruta.setText(null);
    }
     
    if (command.equals("Random numbers")){
     
    Random randomNr = new Random();
     
    int tal;
    for (int i = 0; i < 7; i++) {
    tal = randomNr.nextInt(35);
    textruta.append(tal + " ");
    }
    }
     
    if (command.equals ("Open")) {
    status = openFile ();
     
    } else if (command.equals ("Save")) {
    status = saveFile ();
     
    } else if (command.equals ("Quit") ) {
    System.exit(1);
    }
    }
     
    boolean openFile () {
     
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle ("Open file");
     
    int result = fc.showOpenDialog(this);
     
    if (result == JFileChooser.CANCEL_OPTION) {
    return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {
     
    theFile = fc.getSelectedFile();
    String file_string = readFile (theFile);
     
    if (file_string != null)
    textruta.setText (file_string);
    else
    return false;
    }
    return true;
    }
     
    boolean saveFile() {
    File file = null;
    JFileChooser fc = new JFileChooser();
     
    fc.setSelectedFile (theFile);
     
    int result = fc.showSaveDialog (this);
     
    if (result == JFileChooser.CANCEL_OPTION) {
    return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {
    theFile = fc.getSelectedFile();
     
    return writeFile (theFile, textruta.getText());
    } else {
    return false;
    }
    }
     
    public String readFile (File file) {
     
    StringBuffer fileBuffer;
    String fileString = null;
    String line;
     
    try {
    FileReader in = new FileReader (file);
    BufferedReader dis = new BufferedReader(in);
    fileBuffer = new StringBuffer() ;
     
    while ((line = dis.readLine()) != null) {
    fileBuffer.append(line + "\n");
    }
     
    in.close();
    fileString = fileBuffer.toString();
    }
    catch(IOException e) {
    return null;
    }
    return fileString;
    }
     
    public static boolean writeFile(File file, String dataString) {
    try {
    PrintWriter out =
    new PrintWriter(new BufferedWriter (new FileWriter (file)));
    out.print(dataString);
    out.flush();
    out.close();
    }
    catch (IOException e) {
    return false;
    }
    return true;
    }
     
    public static void main(String [] args) {
    String title = "Lotto";
    Class1 f = new Class1 (title);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
    }
    }

  4. #4
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Make my code follow MVC

    Ok, I'm short on time so I cannot really step through the code for you. So, lets just attack this as a whole.

    Basically, you are wanting to separate your GUI elements from your operating code.

    Think of your program as a person. The GUI elements are the skin and the operating code is the guts. What you are trying to do is separate the skin from the guts. There is catch to doing this however, the human body accepts input from the world around it using the five sense (touch, smell, hear, ect.) but without the guts to determine what to do with that input, there is no point in even having skin. For example, if you touch something hot, that input is transferred from your skin to your guts, then your guts (in this case your brain) decide to pull away from the hot object and send information back to your sensors and you pull away from the hot object (not exactly scientifically correct, but it works nicely as an analogy).

    The same goes with your program. The GUI accepts all the input from the outside world, then passes the input to the operating code to be processed, then passes the processed information back to the GUI to react to. So, when separating the GUI from the operating code you need to remember to preserve the ability to transfer data to and from.

    So, the first step is to sort your code. I want you to go through your code and locate all of the GUI elements. Put all of those GUI elements in a source file. Then go through and locate all of your operating code and put all of those in a source file. At this point, obviously the code will not compile. Now, since your GUI is in control of viewing the world and passing inputted information to the operating code, the class that contains your GUI elements need to be your main. Now what we need to do is go through the operating code and find out what aspects of the code rely on GUI input. Everything that relies on GUI input needs a Mutator Method that will accept the required variables from the GUI. Then you need to go through the GUI and locate all of the GUI information that relies on the operating code. Then go back to the operating code and add an Accessor Method for each bit of information that needs to be sent to the GUI.

    Now that we have the Skin and the Guts separated, we still need to do a few more things. Right now we have a bunch of skin and a bunch of guts but they are useless as individuals. We need to allow them to have access to each other. So to do that in your code, we need to create an instance of the operating code class in your GUI for you to have access to while the program runs. After this instance has been made, you can use it to send GUI information to the operating code and then retrieve information from the operating code using the methods we set up earlier.

    Do that stuff first, and show me your code. We can then tackle separating the Listeners from the GUI if you don't feel like taking a shot at it while doing the above.

    Tell me how that goes and if you need any help or anything clarified ask and I will help.

    Also, what did you think of the analogy? I sort of made it up as I went along. For the purpose of the analogy, think of the Listeners as the neurons, designed to transfer the data the Skin receives.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  5. #5
    Junior Member
    Join Date
    Apr 2010
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Make my code follow MVC

    I have now done some seperating and this is the result:

    The View class:

    import javax.swing.*;
     
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.Random;
     
    public class View extends JFrame {
     
    	private JMenuItem fMenuOpen;
    	private JMenuItem fMenuSave;
    	private JMenuItem fMenuClose;
    	private JMenuItem fMenuRandom;
    	private JMenuItem fMenuClear;
    	private JTextArea textruta;
     
    	public View(String title){
    		super(title);
     
    		Container content_pane = getContentPane();
     
    	    content_pane.setLayout (new BorderLayout());
    	    textruta = new JTextArea();
     
    	    JMenu downMenu = new JMenu ("Arkiv");
    	    content_pane.add(textruta);
     
    	    downMenu.add(fMenuRandom = createMenuItem("Random numbers"));
    	    downMenu.add(fMenuClear = createMenuItem("Clear"));
    	    downMenu.add(fMenuSave  = createMenuItem("Save"));
    	    downMenu.add(fMenuOpen  = createMenuItem("Open"));
    	    downMenu.addSeparator();
    	    downMenu.add(fMenuClose = createMenuItem("Quit"));
     
    	    JMenuBar menuBar = new JMenuBar();
    	    menuBar.add (downMenu);
     
    	    setJMenuBar (menuBar);
    	    setSize (250, 250);
    	    setLocation(400, 100);
     
    	}
    	private JMenuItem createMenuItem(String name) {
    		JMenuItem m = new JMenuItem(name);
    		m.addActionListener(this);
    		return m;
    	}
    	public static void main(String []args){
    		String title = "Lotto";
    	    Class1 f = new Class1 (title);
    	    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	    f.setVisible(true);
    		}
    }


    The Control class:

    import javax.swing.*;
     
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.util.Random;
     
    public class Control extends WindowAdapter implements ActionListener {
    	File theFile = new File ("*.java");
    	private View v;
    	private Model m;
     
    	public Control(View vi){
    		v = vi;
    		m = new Model();
    	}
     
    	public void actionPerformed (ActionEvent e) {
    	    boolean status = false;
     
    	    String command = e.getActionCommand();
    	    if (command.equals("Clear")){
    	    	textruta.setText(null);
    	    }
     
    	    if (command.equals("Random numbers")){
     
    	    	Random randomNr = new Random();
     
    	         int tal;
    	         for (int i = 0; i < 7; i++) {
    	             tal = randomNr.nextInt(35);
    	             textruta.append(tal + " ");
    	         }
    	    }
     
    	    if  (command.equals ("Open")) {
    	    status = openFile ();
     
    	    } else if (command.equals ("Save")) {
    	        status = saveFile ();
     
    	    } else if (command.equals ("Quit") ) {
    	        System.exit(1);
    	    }
    	  } 
     
    	  boolean openFile () {
     
    	      JFileChooser fc = new JFileChooser();
    	      fc.setDialogTitle ("Open file");
     
    	      int result = fc.showOpenDialog(this);
     
    	      if (result == JFileChooser.CANCEL_OPTION) {
    	          return true;
    	      } else if (result == JFileChooser.APPROVE_OPTION) {
     
    	    	  theFile = fc.getSelectedFile();
    	          String file_string = readFile (theFile);
     
    	          if (file_string != null)
    	        	  textruta.setText (file_string);
    	          else
    	              return false;
    	      } 
    	      return true;
    	   } 
     
    	   boolean saveFile() {
    	     File file = null;
    	     JFileChooser fc = new JFileChooser();
     
    	     fc.setSelectedFile (theFile);
     
    	     int result = fc.showSaveDialog (this);
     
    	     if (result == JFileChooser.CANCEL_OPTION) {
    	         return true;
    	     } else if (result == JFileChooser.APPROVE_OPTION) {
    	    	 theFile = fc.getSelectedFile();
     
    	         return writeFile (theFile, textruta.getText());
    	     } else {
    	       return false;
    	     }
    	  } 
     
    	  public String readFile (File file) {
     
    	    StringBuffer fileBuffer;
    	    String fileString = null;
    	    String line;
     
    	    try {
    	      FileReader in = new FileReader (file);
    	      BufferedReader dis = new BufferedReader(in);
    	      fileBuffer = new StringBuffer() ;
     
    	      while ((line = dis.readLine()) != null) {
    	            fileBuffer.append(line + "\n");
    	      }
     
    	      in.close();
    	      fileString = fileBuffer.toString();
    	    }
    	    catch(IOException e) {
    	      return null;
    	    }
    	    return fileString;
    	  } 
     
    	  public static boolean writeFile(File file, String dataString) {
    	    try {
    	       PrintWriter out =
    	         new PrintWriter(new BufferedWriter (new FileWriter (file)));
    	       out.print(dataString);
    	       out.flush();
    	       out.close();
    	    }
    	    catch (IOException e) {
    	       return false;
    	    }
    	    return true;
    	  } 
    }


    What to do next? cause I do not really know how to mutator methods and accessor methods.
    I think the analogy was good! but maybe not the best. Not everybody likes reading about skin and guts and such things but it create a picture in your mind that show you what you need to do.

  6. #6
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Make my code follow MVC

    You've got the V and the C, but I don't see an M. You refer to a Model class in the controller, but this code isn't posted. The model is going to be dependent upon what you wish the program to do, display, save, modify, etc...

  7. #7
    Junior Member
    Join Date
    Apr 2010
    Posts
    8
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Make my code follow MVC

    I do not really know what I should put in the model-class. Here is an example of an program's model-class:

    public class Model {
    private String text;
    public String getRad(){
    text="Nu var det tryckt igen!";
    return text;
    }
    public static void main(String[] args){
    Model l=new Model();
    System.out.println(l.getRad());
    }
    }

    In my program, now when I have the three classes, I have problems with 'textruta' and the actionListener. If you have Eclipse, you will see the problems. I tried to do 'private JTextArea textruta;' and the errors dissapeard. Is this the correct way?
    Last edited by alpvii; November 29th, 2010 at 07:54 AM.

Similar Threads

  1. How to make a graph like this
    By sugarhigh in forum AWT / Java Swing
    Replies: 1
    Last Post: August 27th, 2010, 09:05 AM
  2. Trying to make a bot
    By ighor10 in forum Java Theory & Questions
    Replies: 1
    Last Post: June 11th, 2010, 02:07 PM
  3. What programs shall i make?
    By DarrenReeder in forum Java Theory & Questions
    Replies: 1
    Last Post: December 27th, 2009, 08:31 AM
  4. How to make it???
    By Subhasis Banerjee in forum JavaServer Pages: JSP & JSTL
    Replies: 0
    Last Post: October 29th, 2009, 02:49 PM
  5. Java algorithm for bank program to connect database
    By araujo3rd in forum Algorithms & Recursion
    Replies: 1
    Last Post: December 10th, 2008, 01:34 PM