Swing - Training Etc

snottybugbearSoftware and s/w Development

Nov 3, 2013 (3 years and 10 months ago)

116 views

SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-1
Chapter 10:
Models, Views, and Controllers
1) Introduction............................................................................................................10-2
2) The MVC Process of JButton............................................................................10-3
3) Advantages to using the MVC Architecture.......................................................10-4
4) Pluggable Look and Feel.......................................................................................10-5
5) An MVC Example..................................................................................................10-7
6) Linking the Components.....................................................................................10-10
7) MVC Diagram......................................................................................................10-12
8) ListModel..........................................................................................................10-13
9) AbstractListModel.......................................................................................10-14
10) JTable.................................................................................................................10-16
11) TableModel........................................................................................................10-17
12) MVCList Source Code.........................................................................................10-20

Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-2
Introduction

Models, Views, and Controllers, or MVC, is an
architecture used to design pieces of a graphical interface.

MVC is the architecture used by Swing components,
which are completely written in Java, allowing total control
over their appearance.
 Models – the underlying storage of a component, such as the
state of an object.
 Views – the visual aspect of the component.
 Controllers – this piece takes user input that can change the
model.

Breaking down JButton into its MVC components can be
done easily and provides a good structured example of
MVC.
 Model – the part that is not actually seen. The model of the
JButton is simply a data structure that stores the state of the
button. If the button can be pushed, if it is pushed, etc.
 View – The view of the JButton is what is actually seen by the
user as seen here:


 Controller – The controller listens for the user to click the
button.
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-3
The MVC Process of JButton

The process of a JButton being clicked involves the
following steps:
 When the button is clicked, the controller receives this action.
 The controller then updates the model accordingly such that
when the button is clicked, the controller changes the model to
reflect that the button has been pressed.
 Finally, the model notifies the view that the state of the button
has been changed. So the view of the button is updated to
reflect a pushed look.


This entire process cycles through once for each button
click and once for each button release.

This entire process, including all of the pieces of the MVC
architecture, is wrapped inside a component for ease of
use. (JButton, in this case).

With the Swing components, the word delegate is used to
refer to the combination of the view and controller.
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-4
Advantages to using the MVC Architecture

Multiple views can be based on the same model. This can
be helpful when two displays are based on the same data.
For instance, one component shows a list of numbers
while another component displays the sum of those
numbers.

Views can be changed without affecting the underlying
model so the look of a component can be changed without
much work. A button functions in the same way,
independently of how it looks. Therefore, the model would
not have to be changed, only the view.

It can be difficult to communicate between the controller
and view, because the model must be used as an
intermediate. Because of this, delegates are often used
with models in Swing components with the delegate
serving as the controller and the view.

This makes sense in the case of a JButton as the
clicked button is the one that has its view changed.
 The updated graphic using delegates:

Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-5
Pluggable Look and Feel

Another advantage to the MVC model that should be
mentioned is the pluggable look and feel.

In AWT 1.0, components would use the system widgets,
so that they would have the appearance of the operating
system on which they were running. AWT 1.1 introduced
lightweight components, which used the MVC architecture
to avoid using the system widgets, and thus allowed Java,
instead of the operating system, to specify the look of the
button.

As previously discussed, Swing components follow the
MVC architecture, and are thus lightweight components.
Finally, it is possible to set a certain look and feel for each
of these components.

This can be done using a simple method of the class
UIManager, which throws Exceptions if there is trouble
finding the new look and feel.
try {
UIManager.setLookAndFeel (
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception e) {
//error trying to change look and feel
}

Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-6
Pluggable Look and Feel

The following is a comparison of a button using the Metal
look and feel (default) vs. the Windows look and feel vs.
the Motif look and feel.


The Windows look and feel was set with the above code
and then the Java program was run on a Windows
machine. However, if the program were run on another
operating system, such as Solaris or the MacOS, a
different look and feel would appear.

The default Metal look and feel can be set using the
following syntax instead of the code listed above:
UIManager.setLookAndFeel(
"javax.swing.plaf.metal.MetalLookAndFeel");

For the Motif look and feel, use:
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.motif.MotifLookAndFeel");

It is the hope that in the future many different look and
feels will be available. The file, LookTest.java, will
allow you to experiment with the look and feels mentioned
above.
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-7
An MVC Example

The following MVC example will attempt to create the
three pieces of the MVC architecture including a container
for the three pieces.

This example will display a button (controller) and a list
(view) that will be based on a vector of numbers (model).
The button, when clicked, will add another number to the
list.

The model will look like this:
ListModel.java
1. import java.util.*;
2. import javax.swing.event.*;
3.
4. public class ListModel {
5. Vector v;
6. ChangeListener connectToView;
7. public ListModel() {
8. v = new Vector();
9. }
10. public void add( int s ) {
11. v.add(new String(new Integer(s).toString()));
12. changed();
13. }
14. public Vector getData() {
15. return v;
16. }
17. public void changed() { //inform the view
18. ChangeEvent ce = new ChangeEvent(this);
19. connectToView.stateChanged(ce);
20. }
21. public void setChangeListener(ChangeListener c ){
22. connectToView = c;
23. }
24. }
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-8
An MVC Example

The model will have the following functionality:
 Vector v – to store all of the numbers in the list
 ChangeListener connectToView – to notify the view that
the model has been changed
 changed – called when the model is changed, thus, allowing
the model to notify the view.
 add (int) – the vector will be updated with the following
value
 getData – simply returns the underlying Vector that can be
used by the View to display the data.
 setChangeListener( ChangeListener ce ) – allows
the ChangeListener to be set.
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-9
An MVC Example

Next, the view is simply a wrapper class around the swing
class JList. This view extends JList, and only adds
one method.
ListView.java
1. import javax.swing.*;
2. import java.util.Vector;
3.
4. public class ListView extends JList {
5. public void changed(Vector v) {
6. setListData(v);
7. }
8. }

The only relevant method of the list view is the changed
method, which is called by the Model through the
ChangeListener.

Finally, the controller is going to be a JButton and will be
linked to the model in the container class.

Now that the three pieces of the MVC architecture have
been established, the container class must be created,
providing the appropriate links between the components.
The file, MVCList.java, serves this purpose.

First, to link the controller to the model, an
ActionListener will be used. This allows the controller
to notify the model whenever an action is performed on
the button (getting clicked).
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-10
Linking the Components
MVCList.java (snippet)
1. jb = new JButton("Add to List");
2. //linking the controller to the model
3. jb.addActionListener(
4. new ActionListener() {
5. public void actionPerformed(ActionEvent ae){
6. lm.add(x++);
7. }
8. });

This snippet uses the AWT event model. An
ActionListener is any class that implements the
interface ActionListener. Instead of creating an entire
class, because the only method that will be used is the
actionPerformed method, an anonymous class is
created.

The anonymous class only defines the
actionPerformed method, which calls the model’s add
method (line 6).

When the JButton (jb) is clicked, the model’s add
method will be called, compelling the model to be updated
whenever the controller is used. However, the view will
not change because it is not yet linked to the model.

The final link between the model and the view will be done
using Swing’s ChangeListeners. Support for this has
already been included in both the model and the view.
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-11
Linking the Components
MVCList.java (snippet)
1. private class ModelToViewAdapter
2. implements ChangeListener {
3. ListModel lm;
4. ListView lv;
5.
6. public ModelToViewAdapter(ListModel l,
7. ListView v) {
8. lm = l;
9. lv = v;
10. }
11.
12. public void stateChanged(ChangeEvent ce) {
13. lv.changed(lm.getData());
14. }
15. }

An adapter class is created within the container class.
This adapter implements ChangeListener so that the
model can use this adapter to communicate with the view.

All of the work being done is in the stateChanged
method, where the changed method of the view is called,
sending the data from the model to the view.
ModelToViewAdapter mToA =
new ModelToViewAdapter( lm, lv );
lm.setChangeListener(mToA);

Now, the model is set to use the correct
ChangeListener when it is changed.
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-12
MVC Diagram

The MVC architecture, replacing the abstract components
with the actual components used in the previous
examples leaves the following:

Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-13
ListModel

Although the previous example implements the MVC
architecture, it uses the fact that the JList object can
represent the data stored as a Vector.

Suppose a list was still being represented, but a Vector
was not sufficient for storing this list. In other words, a
different model must be used, one which does not store
data as a Vector.

In this case, JList would not function properly. However,
JList does offer support for this situation.

There exists an interface called ListModel that if
implemented, can display the data using a JList.

To create a model that implements ListModel, the
following methods must be implemented
 Object getElementAt(int index)
 int getSize()
 void addListDataListener(ListDataListener l)
 void removeListDataListener(ListDataListener l)

With the above methods, JList can display a list based
on the data and can be constructed with:
 new JList( ListModel lm );
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-14
AbstractListModel

Swing also provides an AbstractListModel that,
unlike the ListModel, is a class and not an interface.

The AbstractListModel has built-in support for event
listeners so only two of the above methods must be
implemented, getElementAt and getSize.

A complete example of using the AbstractListModel
is shown here.
AListModel.java
1. import javax.swing.*;
2.
3. public class AListModel extends AbstractListModel {
4. int size;
5. Integer []data;
6.
7. public AListModel( int n ) {
8. size = n;
9. data = new Integer[size];
10. for (int i = 0; i < n; i++) {
11. data[i] = new Integer(i);
12. }
13. }
14.
15. public Object getElementAt( int x ) {
16. return data[x];
17. }
18.
19. public int getSize() {
20. return size;
21. }
22. }
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-15
AbstractListModel

The above is a list model that simply displays the integers
from zero to the size minus one. This model, in fact, only
connects to the view and has no way of being controlled.

To display this list, a JList can be used.
AListUse.java
1. import javax.swing.*;
2. import java.awt.*;
3.
4. public class AListUse extends JFrame {
5. public AListUse() {
6. Container p = getContentPane();
7. setSize(400,400);
8. JList jl = new JList( new AListModel(10));
9. p.add(jl);
10. setVisible(true);
11. }
12. public static void main( String [] args) {
13. new AListUse();
14. }
15. }
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-16
JTable

Swing contains a component called JTable that can be
used to display tables of data.

You can make a JTable by passing it the data and
column headings. A complete example can be found in
the file, TableWithData.java.
Object [][] data = {
{"one", "two", "three"},
{"four", "five", "six"}
};
String [] cols = {"col1", "col2", "col3"};
JTable table = new JTable(data, cols);
JscrollPane jsp = new JscrollPane(table);
getContentPane().add(jsp, BorderLayout.Center);




A JTable should be placed inside a JScrollPane if you
want the column headers to be visible.

You can also supply the JTable with a Vector of
Vectors for the data, and a Vector of Strings for the
column headings.

Internally the JTable uses an object of type
TableModel to store the data.
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-17
TableModel

Most of the time, the Vector class is sufficient for the
underlying storage of a model that has a list style view.

There is a swing component, JTable, which represents
data in a table or matrix format.

A data structure that implements TableModel can be
used in this case.
 It must implement these methods.
public interface TableModel {
int getRowCount();

int getColumnCount();

String getColumnName(int columnIndex);

Class getColumnClass(int columnIndex);

boolean isCellEditable(int rowIndex,
int columnIndex);

Object getValueAt(int rowIndex, int columnIndex);

void setValueAt(Object aValue, int rowIndex,
int columnIndex);

void addTableModelListener( TableModelListener l);

void removeTableModelListener(
TableModelListener l);
}

Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-18
TableModel

The JTable can be constructed with a TableModel as
its argument just like the JList and ListModel.
 new JTable( TableModel tm )



Also included with Swing, is the AbstractTableModel
class that handles many of the common features of
TableModels, including TableModelListeners.

Instead of implementing TableModel, it is often easier to
extend the abstract class, AbstractTableModel, as
demonstrated by the application created in the files,
TableUsage.java and MyTableModel.java. Then
only the following methods must be defined:
 public int getRowCount()
 public int getColumnCount()
 public Object getValueAt(int row, int column)

Furthermore, the abstract class will handle the listeners.
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-19
TableModel

By only defining the above methods, the JTable will not
be editable, because the setValueAt and
isCellEditable methods have not been defined.

Also included with Swing is the DefaultTableModel.
This is an implementation of the TableModel interface
that stores its data in a Vector of Vectors. It contains
many methods to allow you to manipulate the data, such
as adding and deleting rows and columns.

The example presented above could have been written to
explicitly create a DefaultTableModel. This would
create a JTable in which you could manipulate the
dataset using the methods of DefaultTableModel.
Object [][] data = {
{"one", "two", "three"},
{"four", "five", "six"}
};
String [] cols = {"col1", "col2", "col3"};
DefaultTableModel dtm =
new DefaultTableModel(data, cols);
JTable table = new JTable(dtm);
JscrollPane jsp = new JscrollPane(table);
getContentPane().add(jsp,BorderLayout.Center);
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-20
MVCList Source Code
MVCList.java
1. import javax.swing.*;
2. import javax.swing.event.*;
3. import java.awt.event.*;
4. import java.awt.*;
5.
6. public class MVCList extends JFrame {
7. ListView lv; //the view
8. ListModel lm; //the model
9. JButton jb; //will serve as the controller
10. int x = 0;
11.
12.
13. private class ModelToViewAdapter
14. implements ChangeListener {
15. ListModel lm;
16. ListView lv;
17. public ModelToViewAdapter(ListModel l,
18. ListView v) {
19. lm = l;
20. lv = v;
21. }
22. public void stateChanged(ChangeEvent ce) {
23. lv.changed(lm.getData());
24. }
25. }
26.
27. public MVCList() {
28. setSize(300,500);
29.
30. lv = new ListView();
31. lm = new ListModel();
32.
33. jb = new JButton("Add to List");
34. //linking the controller to the model
35. jb.addActionListener(
36. new ActionListener() {
37. public void actionPerformed(ActionEvent ae){
38. lm.add(x++);
39. }
40. });
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-21
MVCList Source Code
MVCList.java - continued
41.
42. ModelToViewAdapter mToA =
43. new ModelToViewAdapter(lm, lv);
44. //link model to view
45. lm.setChangeListener(mToA);
46.
47. Container p = getContentPane();
48. p.setLayout(new BorderLayout());
49. p.add(jb, BorderLayout.SOUTH);
50. p.add(lv);
51. setVisible(true);
52. }
53.
54. public static void main( String [] args) {
55. new MVCList();
56. }
57. }
Evaluation
Evaluation

Copy
Copy



SWING C
HAPTER
10:

M
ODELS
,

V
IEWS
,
AND
C
ONTROLLERS

©2006 /training/etc Inc. REPRODUCTION OF THESE MATERIALS IS PROHIBITED.
10-22
Exercises
1. Using the example code from this chapter, create a new
view that instead of displaying every element in the
model, displays the total value of all elements in the
model. Note that the model or controller should not have
to be changed. Extending a JTextField should be
enough for this view.
 The elements in the Vector are stored as Strings so they
must be converted before being summed. (Remember the
Integer class?)
2. Change the look and feel of the above exercise to Motif.
3. Implement a model for a JTable extending
AbstractTableModel.
 Each cell should contain a String.
 Your model should take the number of rows and columns in its
constructor.
 The cells in the JTable should also be editable, making this
JTable a delegate.
 Finally, create a class that draws a JTable based on your
model.


Evaluation
Evaluation

Copy
Copy