1

When you create a view (in this case it is Swing panel) you add multiple components such as buttons, labels, text fields etc.

Then you have a controller for this view. The view will be used by the controller for different models. Each model requires different components to be enabled/disabled (not all components should be active always). What I have done up to now is to create a method in the view named for instance: carMode() which does the required configuration in the view and the I call this method in the controller based on some conditions.

Controller code:

if (something == car) { view.carMode() }

However, sometimes you will have need multiple different states for you view and I wonder if this approach could be replaced by something better?

tereško
  • 58,060
  • 25
  • 98
  • 150
LuckyLuke
  • 47,771
  • 85
  • 270
  • 434

2 Answers2

1

Consider using an enum in which the elements implement a common interface to effect a strategy pattern. You can let each element implement the interface directly, as oulined here, or let each element have an instance variable that implements the interface, as shown here. To manipulate the view, a concrete implementation can do any of several things:

  • Configure a single panel by enabling and disabling components.

  • Select a particular panel in a CardLayout.

  • Navigate to particular panel in a JTabbedPane.

Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
  • Would you mind showing an example? And if you are referring to an element as component in Swing for instance, what do you do with single elements such as JButton etc? I may misunderstood the answer. – LuckyLuke Mar 08 '13 at 13:04
  • 1
    I'd be use CardLayout as start point, any idea about disabling already visible JComponents couldn't be users friedly, have to calculating with that too, but idea to hold separate JPanel with reduced and really required number of JCOmponents is quite safe of possible ways – mKorbel Mar 08 '13 at 13:16
  • Here, _element_ refers to the individual `enum` instances. Sorry, I have no better examples than those cited. – trashgod Mar 08 '13 at 13:16
0

A better way to do this is a generic view. Create a viewBase class wich contains the stuff, which can shared among the views. Then create specialized views. One for each mode. The controller than can initialize the specefic view.

if(sometin == car) { view = new CarView()}

The second advantage is that you have the stuff for the specefic views in specefic file. This is more flexible and less complex

mstrewe
  • 441
  • 3
  • 15