Skip to content

Instantly share code, notes, and snippets.

@ryan-beckett
Created January 24, 2012 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryan-beckett/1667503 to your computer and use it in GitHub Desktop.
Save ryan-beckett/1667503 to your computer and use it in GitHub Desktop.
A quick demonstration of the MVC pattern.
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment