Skip to content

Instantly share code, notes, and snippets.

@Sammy30
Created June 24, 2014 11:42
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sammy30/7ebc606e7bb76cefac0f to your computer and use it in GitHub Desktop.
Save Sammy30/7ebc606e7bb76cefac0f to your computer and use it in GitHub Desktop.
Sample MVC Java
package mvc.controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import mvc.models.*;
import mvc.views.*;
public class Controller {
private Model model;
private View view;
private ActionListener actionListener;
public Controller(Model model, View view){
this.model = model;
this.view = view;
}
public void contol(){
actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
linkBtnAndLabel();
}
};
view.getButton().addActionListener(actionListener);
}
private void linkBtnAndLabel(){
model.incX();
view.setText(Integer.toString(model.getX()));
}
}
package mvc;
import javax.swing.SwingUtilities;
import mvc.models.*;
import mvc.views.*;
import mvc.controllers.*;
public class Main
{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
Model model = new Model(0);
View view = new View("-");
Controller controller = new Controller(model,view);
controller.contol();
}
});
}
}
package mvc.models;
public class Model {
private int x;
public Model(){
x = 0;
}
public Model(int x){
this.x = x;
}
public void incX(){
x++;
}
public int getX(){
return x;
}
}
package mvc.views;
import javax.swing.*;
import java.awt.BorderLayout;
public class View {
private JFrame frame;
private JLabel label;
private JButton button;
public View(String text){
frame = new JFrame("View");
frame.getContentPane().setLayout(new BorderLayout());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
frame.setVisible(true);
label = new JLabel(text);
frame.getContentPane().add(label, BorderLayout.CENTER);
button = new JButton("Button");
frame.getContentPane().add(button, BorderLayout.SOUTH);
}
public JButton getButton(){
return button;
}
public void setText(String text){
label.setText(text);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment