I am trying to implement the MVC paradigm in Java (Swing) using multithreading. Currently, I am extending the View class with the Observer Class and the and the Model Class with the Observable Class and its working fine (MY code is bulit along this example: http://austintek.com/mvc/). The controller class simply calls the corresponding model and view functions and there is a main "glue" program that sets up everything. However, this approach does not utilize threads. Is there any way to implement this by using threads and the Observer/Observable class at the same time?
(My aim is to implement each of the M, V and C as a separate thread)
The following is part of my View code:
public class View implements Observer
{
/*************************************** View *************************************
**
** This function is the constructor of the View class.
**
** PRE: <nothing>
** POST: the GUI is created and the directory is displayed on the screen.
** RETURN: <N/A>
**
**/
View(String name)
{
threadName = name;
//frame in constructor and not an attribute as doesn't need to be visible to whole class
JFrame frame = new JFrame("simple MVC");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addElements(frame); // this is implemented separately
// frame.addWindowListener(new CloseListener());
frame.setSize(900, 732);
// frame.setLocation(100,100);
/** Display the window **/
//frame.pack();
frame.setVisible(true);
}// View
And following is part of my Model code:
public class Model extends java.util.Observable
{
/****************** variable DECLARATIONS *********************/
// The hash table in which the directory is stored
private Hashtable<String, Integer> tel_dir
= new Hashtable<String, Integer>();
// The path of the telephone directory during runtime
private URL filePath
= Model.class.getClassLoader().getResource("directory.txt");
// the name of the thread
private String threadName;
/****** private Thread t; ******/
// the object in which the message is sent to the view
private Message message = new Message();
/** GETTERS and SETTERS **/
....
/*************************************** Model *************************************
**
** This function is the constructor of the model class.
**
** PRE: <nothing>
** POST: the telephone directory is input from the file and stored in a hash
** table.
** RETURN: <N/A>
**
**/
Model(String name)
{
int phone_num;
String customer_name;
Scanner scanner = null;
threadName = name;
/** Opening the handle to the file containing the telephone directory **/
try
{
scanner = new Scanner(new File(filePath.getPath()));
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
/** Inputting from the file and storing it in the hash table **/
while (scanner.hasNextInt())
{
phone_num = scanner.nextInt();
customer_name = scanner.nextLine();
customer_name = customer_name.trim();
tel_dir.put(customer_name, phone_num);
}
}// Model