for the purpose of my application i need to create several identical views that should behave and response to the same events. Should i instanciate each identical views that i need and hold this list of views in my controller, or there are better ways of handling this ? Thanks.
Asked
Active
Viewed 113 times
1 Answers
2
From what I understand... You should follow your thinking.
Have a list of views that you install to a controller. And if the event occurs go through the list of views and update all of them.
EDIT1: Here is a very simple example showing how it might be done.
import java.awt.Color;
import java.awt.Component;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class ManyViewsTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
View v1 = new View();
View v2 = new View();
View v3 = new View();
View v4 = new View();
View v5 = new View();
JPanel contentPane = new JPanel();
contentPane.add(v1);
contentPane.add(v2);
contentPane.add(v3);
contentPane.add(v4);
contentPane.add(v5);
JFrame f = new JFrame();
f.setContentPane(contentPane);
f.setSize(800, 600);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Controller c = new Controller(f);
f.setVisible(true);
}
});
}
}
class Controller
{
private List<View> views;
public Controller(JFrame f)
{
this.views = new ArrayList<View>();
f.addMouseListener(mL);
for(Component c: f.getContentPane().getComponents())
{
if(c instanceof View)
views.add((View)c);
}
}
public void updateView(String text)
{
for(View v: views)
v.setLabelText(text);
}
private MouseListener mL = new MouseAdapter()
{
int pressCounter = 0;
@Override
public void mousePressed(MouseEvent e)
{
super.mousePressed(e);
updateView("mousePressed, pressCounter="+(++pressCounter));
}
};
}
class View extends JPanel
{
private static final long serialVersionUID = 1L;
private JLabel label;
public View()
{
this.label = new JLabel("Initialized");
label.setBorder(BorderFactory.createLineBorder(Color.GREEN));
add(label);
}
public void setLabelText(String text)
{
label.setText(text);
}
}

Boro
- 7,913
- 4
- 43
- 85
-
@LionO no problem hope it is useful for you. Good luck – Boro May 04 '11 at 17:55
-
+1 In this example, the implicit _model_ is a `List
`. In the more typical implementation, the _controller_ listens to the _model_ and notifies any registered _view_ to update itself, as shown [here](http://stackoverflow.com/questions/3066590/gui-problem-after-rewriting-to-mvc/3072979#3072979). – trashgod May 04 '11 at 20:05