Results 1 to 9 of 9
  1. #1
    chopram is offline Member
    Join Date
    Jun 2008
    Posts
    4
    Rep Power
    0

    Default Model View Controller with Java

    Hi Guys,
    I am quite experienced in programming with Java. I have though come accross a small problem, I don't know how to implement the MVC pattern. I understand the concepts of the MVC pattern and I was hoping that someone on this forum could help.

    I have a model which is just a class that adds 2 integers together and returns the answer. The code is shown below.

    ================================================== ===
    public class Adder
    {

    public int add(int x, int y)
    {
    return x + y;
    }
    }

    ================================================== ===

    Now what I want to do is apply the MVC pattern to the above model. I want to have a Swing interface with 2 textboxes and an equals button which then displays the answer. How do I apply the MVC pattern?

  2. #2
    Zosden's Avatar
    Zosden is offline Senior Member
    Join Date
    Apr 2008
    Posts
    384
    Rep Power
    7

    Default

    one class holds your gui. One class is a controller it passes info from gui to model. Look up reflection also its in the api. The way I do it is one a button is clicked it goes from an Actionlistener class I made to the controller that then goes to the model.
    My IP address is 127.0.0.1

  3. #3
    chopram is offline Member
    Join Date
    Jun 2008
    Posts
    4
    Rep Power
    0

    Default Mvc

    Any simple example of a program you can show me using MVC???

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    This looks familiar to a post that was answered recently (last day or so) in the Sun Java forums. Is that your post as well?

  5. #5
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    
    public class MvcTest {
        public static void main(String[] args) {
            Dimension d = new Dimension(400, 400);
            MvcModel model = new MvcModel(50,50,200,100,2,3);
            MvcView view = new MvcView(model, d);
            MvcController controller = new MvcController(model, view);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(view);
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
            controller.start();
        }
    }
    
    class MvcModel {
        int x;
        int y;
        int width;
        int height;
        int dx;
        int dy;
        int minSize;
        int maxSize;
    
        public MvcModel(int x, int y, int w, int h, int dx, int dy) {
            this.x = x;
            this.y = y;
            width = w;
            height = h;
            this.dx = dx;
            this.dy = dy;
            minSize = height;
            maxSize = 3*height;
        }
    
        public void pulse() {
            if(height + dy < minSize || height + dy > maxSize) {
                dy *= -1;
            }
            height += dy;
        }
    
        public void reverse() {
            dx *= -1;
        }
    
        public void advance() {
            x += dx;
        }
    
        public String toString() {
            return "MvcModel[x:" + x + ", y:" + y +
                          ", width:" + width +
                          ", height:" + height + "]";
        }
    }
    
    class MvcView extends JPanel {
        MvcModel model;
        Dimension size;
    
        public MvcView(MvcModel model, Dimension size) {
            this.model = model;
            this.size = size;
        }
    
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.red);
            g2.drawRect(model.x, model.y, model.width, model.height);
        }
    
        public Dimension getPreferredSize() {
            return size;
        }
    }
    
    class MvcController implements Runnable {
        MvcModel model;
        MvcView view;
        Thread thread;
        boolean running = false;
        final long DELAY = 100;
    
        public MvcController(MvcModel model, MvcView view) {
            this.model = model;
            this.view = view;
        }
    
        public void start() {
            if(!running) {
                running = true;
                thread = new Thread(this);
                thread.setPriority(Thread.NORM_PRIORITY);
                thread.start();
            }
        }
    
        public void run() {
            while(running) {
                try {
                    Thread.sleep(DELAY);
                } catch(InterruptedException e) {
                    running = false;
                    System.out.println("Interrupt");
                }
                model.pulse();
                changeLocation();
                view.repaint();
            }
        }
    
        private void changeLocation() {
            int w = view.getWidth();
            if(model.x + model.dx < 0 || model.x + model.width + model.dx > w) {
                model.reverse();
            }
            model.advance();
        }
    }

  6. #6
    chopram is offline Member
    Join Date
    Jun 2008
    Posts
    4
    Rep Power
    0

    Default

    thanks for the code hardwired. How would you implement a MVC using the Adder class that I've shown (with textboxes, buttons, etc) because your program is very good but there are not any buttons or text boxes. please help. thank you.

  7. #7
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    I'll use the MvcTest example to demonstrate, posting only the changes.
    The entire MvcTest class.
    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class MvcTest implements ActionListener {
        MvcView view;
        MvcController controller;
    
        public MvcTest() {
            Dimension d = new Dimension(400, 400);
            MvcModel model = new MvcModel(50,50,200,100,2,3);
            view = new MvcView(model, d);
            controller = new MvcController(model, view);
        }
    
        public void actionPerformed(ActionEvent e) {
            String ac = e.getActionCommand();
            if(ac.equals("START"))
                controller.start();
            if(ac.equals("STOP"))
                controller.stop();
        }
    
        private JPanel getView() {
            return view;
        }
    
        private JPanel getControlPanel() {
            JPanel panel = new JPanel();
            String[] ids = { "start", "stop" };
            for(int j = 0; j < ids.length; j++) {
                JButton button = new JButton(ids[j]);
                button.setActionCommand(ids[j].toUpperCase());
                button.addActionListener(this);
                panel.add(button);
            }
            return panel;
        }
    
        public static void main(String[] args) {
            MvcTest test = new MvcTest();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test.getView());
            f.add(test.getControlPanel(), "Last");
            f.pack();
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }
    Add this method to the MvcController class.
    Java Code:
        public void stop() {
            running = false;
            if(thread != null)
                thread.interrupt();
            thread = null;
        }
    Other classes unchanged.

    Imagination is the key to putting things together with mvc.

  8. #8
    chopram is offline Member
    Join Date
    Jun 2008
    Posts
    4
    Rep Power
    0

    Default

    thanks again hardwired. i dont want to sound dumb, but i think to aid my understanding of mvc would it be possible for you to develop a mvc for my adder model. your code at the moment is great but its too complex for me (no offence) im just a little inexperienced. thanks for all your help.

  9. #9
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class MvcAdderTest {
        // Some choose to put this [i]main[/i] method
        // in the view class.
        public static void main(String[] args) {
            MvcAdderModel model = new MvcAdderModel();
            MvcAdderView view = new MvcAdderView();
            MvcAdderController controller =
                new MvcAdderController(model, view);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(view.getView());
            f.setSize(300,200);
            f.setLocation(200,200);
            f.setVisible(true);
        }
    }
    
    class MvcAdderModel {
        public int add(int x, int y) {
            return x + y;
        }
    }
    
    class MvcAdderView {
        JTextField one;
        JTextField two;
        JButton button;
        JLabel label;
        JPanel panel;
    
        public MvcAdderView() {
            // initialize components
            one = new JTextField(8);
            two = new JTextField(8);
            label = new JLabel();
            label.setHorizontalAlignment(JLabel.CENTER);
            label.setFont(label.getFont().deriveFont(16f));
            button = new JButton("add");
            // assemble top
            JPanel top = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets.top = 5;
            gbc.weightx = 1.0;
            top.add(one, gbc);
            top.add(two, gbc);        
            // bottom section
            JPanel last = new JPanel();
            last.add(button);
            // put it all together
            panel = new JPanel(new BorderLayout());
            panel.add(top, "First");
            panel.add(label);
            panel.add(last, "Last");
        }
    
        public String getOneText() { return one.getText(); }
    
        public String getTwoText() { return two.getText(); }
    
        public void setLabel(String result) {
            label.setText(result);
            label.repaint();
        }
    
        public JPanel getView() {
            return panel;
        }
    
        public void register(ActionListener al) {
            one.addActionListener(al);
            two.addActionListener(al);
            button.addActionListener(al);
        }
    }
    
    class MvcAdderController implements ActionListener {
        MvcAdderModel model;
        MvcAdderView view;
        boolean errored = false; // used to avoid bogus results
    
        public MvcAdderController(MvcAdderModel model, MvcAdderView view) {
            this.model = model;
            this.view = view;
            view.register(this);
        }
    
        public void actionPerformed(ActionEvent e) {
            errored = false;
            String one = view.getOneText();
            String two = view.getTwoText();
            System.out.printf("one = %s  two = %s%n", one, two);
            if(one.equals("") || two.equals(""))
                return;
            int n1 = parse(one);
            int n2 = parse(two);
            int sum = model.add(n1, n2);
            System.out.printf("n1 = %d  n2 = %d  sum = %d%n", n1, n2, sum);
            String s = errored ? "error!" : String.valueOf(sum);
            view.setLabel(s);
        }
    
        private int parse(String s) {
            int n = -1;
            try {
                n = Integer.parseInt(s.trim());
            } catch(NumberFormatException e) {
                System.out.println("parse error: " + e.getMessage());
                // This method must return an [i]int[/i] and there is no
                // way to test the returned value for error-checking.
                // So use the "errored" flag to warn the user that we
                // could not parse a text entry.
                errored = true;
            }
            return n;
        }
    }

Similar Threads

  1. Model-View-Controller
    By Abnoba12 in forum Advanced Java
    Replies: 1
    Last Post: 05-15-2008, 01:32 PM
  2. Unable to view japanese in java applet
    By rogermakrm in forum Java Applets
    Replies: 5
    Last Post: 01-16-2008, 07:07 AM
  3. Create view of files in java-Swing
    By Albert in forum AWT / Swing
    Replies: 1
    Last Post: 07-06-2007, 07:06 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •