Sascha's Wiki

MVC Beispiel

Die Klassen und Pakete

  • mvc.controller
    • Controller.java
  • mvc.model
    • IPerson.java
    • Person.java
    • PersonCollection.java
  • mvc.sample
    • MVCSample.java
  • mvc.view
    • IView.java
    • PersonView.java

mvc.controller

Controller.java

package mvc.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import mvc.model.Person;
import mvc.model.PersonCollection;
import mvc.view.IView;

public class Controller implements ActionListener, PropertyChangeListener {
    
    IView view;
    PersonCollection model;
    
    public Controller(IView view, PersonCollection model) {
        this.view = view;
        view.addActionListener(this);
        this.model = model;
        model.addPropertyChangeListener(this);
    }
    
    @Override
    public void actionPerformed(ActionEvent e) {
        switch (e.getActionCommand()) {
            case "add":
                Person addPerson = view.getAddPerson();
                model.add(addPerson);
                break;
            case "remove":
                Person removePerson = view.getRemovePerson();
                model.remove(removePerson);
                break;
        }
    }

    @Override
    public void propertyChange(PropertyChangeEvent evt) {
        //
    }
}

mvc.model

IPerson.java

package mvc.model;

public interface IPerson {
    
    public String getName();

    public void setName(String name);

    public String getAge();

    public void setAge(String age);
    
}

Person.java

package mvc.model;

public class Person implements IPerson{

    public Person(String name, String age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return String.format("%s (%s)", name, age);
    }
    
    private String name;
    
    private String age;

    @Override
    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String getAge() {
        return age;
    }

   
    @Override
    public void setAge(String age) {
        this.age = age;
    }

    @Override
    public String getName() {
        return name;
    }
    
    
    
    
}

PersonCollection.java

package mvc.model;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;

public class PersonCollection extends ArrayList<Person> {

    PropertyChangeSupport pcs = new PropertyChangeSupport(this);

    @Override
    public boolean add(Person e) {
        boolean add = super.add(e); //To change body of generated methods, choose Tools | Templates.
        pcs.firePropertyChange("add", null, e);
        return add;
    }

    @Override
    public boolean remove(Object o) {
        boolean remove = super.remove(o); //To change body of generated methods, choose Tools | Templates.
        pcs.firePropertyChange("remove", o, null);
        return remove;
    }
    
    
    public void addPropertyChangeListener(PropertyChangeListener l){
        pcs.addPropertyChangeListener(l);
    }
    
    public void removePropertyChangeListener(PropertyChangeListener l){
        pcs.removePropertyChangeListener(l);
    }
}

mvc.sample

MVCSample.java

package mvc.sample;

import java.awt.EventQueue;
import mvc.controller.Controller;
import mvc.model.PersonCollection;
import mvc.view.PersonView;
import mvc.view.View2;

public class MVCSample {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        PersonCollection model = new PersonCollection();
        final PersonView view = new PersonView(model);
        final View2 view2 = new View2(model);
        Controller controller = new Controller(view2, model);
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                view2.setVisible(true);
            }
        });
    }
}

mvc.view

IView.java

package mvc.view;

import java.awt.event.ActionListener;
import mvc.model.Person;

public interface IView {
    
    public void addActionListener(ActionListener listener);
    
    public Person getAddPerson();
    
    public Person getRemovePerson();
    
}

PersonView.java

package mvc.view;

import java.awt.EventQueue;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.DefaultListModel;
import mvc.model.Person;
import mvc.model.PersonCollection;

public class PersonView extends javax.swing.JFrame implements IView{
    
    private ActionListener controller;
    private PersonCollection personModel;
    private DefaultListModel<Person> model = new DefaultListModel<>();

    /**
     * Creates new form PersonView
     */
    public PersonView(PersonCollection coll) {
        initComponents();
        personModel = coll;
        coll.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                EventQueue.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        PersonView.this.model.clear();
                        for (Person person : personModel) {
                            PersonView.this.model.addElement(person);
                        }                        
                    }
                });
            }
        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        Liste = new javax.swing.JList<Person>();
        remove = new javax.swing.JButton();
        add = new javax.swing.JButton();
        Name = new javax.swing.JTextField();
        Alter = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        Liste.setModel(model
        );
        jScrollPane1.setViewportView(Liste);

        remove.setText("remove");
        remove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actionCommandDelegate(evt);
            }
        });

        add.setText("add");
        add.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actionCommandDelegate(evt);
            }
        });

        Name.setText("Name");

        Alter.setText("Alter");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 441, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(Name)
                    .addComponent(Alter)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(add)
                            .addComponent(remove))
                        .addGap(0, 162, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(Name, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(Alter, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(add)
                .addGap(78, 78, 78)
                .addComponent(remove)
                .addContainerGap(85, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void actionCommandDelegate(java.awt.event.ActionEvent evt) {                                       
        if (controller == null) {
            return;
        }
        controller.actionPerformed(evt);
    }                                      
    // Variables declaration - do not modify                     
    private javax.swing.JTextField Alter;
    private javax.swing.JList<Person> Liste;
    private javax.swing.JTextField Name;
    private javax.swing.JButton add;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton remove;
    // End of variables declaration                   

    @Override
    public Person getAddPerson() {
        return new Person(Name.getText(), Alter.getText());
    }
    
    @Override
    public Person getRemovePerson() {
        return Liste.getSelectedValue();
    }

    @Override
    public void addActionListener(ActionListener listener) {
        controller = listener;
    }

    
}

java/allgemein/mvc-beispiel.txt · Zuletzt geändert: 2016/11/11 18:00 von changer