public
Created

A quick demonstration of the MVC pattern.

  • Download Gist
EmployeeClient.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
 
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
 
public class EmployeeClient {
 
public static void main(String[] args) {
 
EmployeeView view = new EmployeeView();
EmployeeModel model = new EmployeeModel();
EmployeeController cntlr = new EmployeeController(view, model);
view.open();
 
}
}
 
class EmployeeModel {
 
private String[] names = { "Ryan", "Mike", "Joe" };
private int index;
 
public EmployeeModel() {
}
 
public String getNextName() {
return names[index++ % names.length];
}
 
}
 
class EmployeeController implements ActionListener {
 
private EmployeeView view;
private EmployeeModel model;
 
public EmployeeController(EmployeeView v, EmployeeModel m) {
view = v;
model = m;
view.setController(this);
}
 
@Override
public void actionPerformed(ActionEvent e) {
view.setName(model.getNextName());
}
}
 
class EmployeeView {
 
private JFrame win;
private JPanel frm;
private JLabel name;
private JButton action;
 
public EmployeeView() {
 
win = new JFrame("Employee Form");
frm = new JPanel();
name = new JLabel("Empty");
action = new JButton("Next Employee");
 
frm.setLayout(new BoxLayout(frm, BoxLayout.Y_AXIS));
frm.add(name);
frm.add(action);
win.add(frm);
}
 
public void setName(String name) {
this.name.setText(name);
}
 
public void setController(ActionListener cntlr) {
action.addActionListener(cntlr);
}
 
public void open() {
win.setSize(300, 300);
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
win.setVisible(true);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.