File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes how to implement mvc or observer pattern on this java code ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "how to implement mvc or observer pattern on this java code ?" Watch "how to implement mvc or observer pattern on this java code ?" New topic
Author

how to implement mvc or observer pattern on this java code ?

benny rusli
Ranch Hand

Joined: Jan 15, 2005
Posts: 72
Hello people,

i would like to know whether i can do this or not. I have written a small java GUI program and this program should add the value from the JTextField incrementelly if we push the return key. Now i am wondering how to split it into mvc or observer pattern. I have read and known the basic the difference among model view controller. Model ata structure, no visual representation, View: visual representations and Controller: handling of events. The MVC Interaction could be described like this : The controller updates the model, the model tells the view that data has changed, finally the view redrawn. Here is my code.

the whole code without mvc :




and i try to split it into mvc without success, i am getting stuck


Any help will be appreciated.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38519
    
  23
Your app. seems to work in its original format, but you can't get input from the JTextField after you have pushed the "reset" button. You would have to add a KeyListener to the JTextField to get it to work again. Or, an "add" button.

You are right to pull out the main() method into a class of its own. BTW: Whenever you create a JFrame or a subclass of JFrame, be sure to call its setDefaultCloseOperation method; one usually chooses the operation which exits on close (see API).

Yes, I know you will find lost of examples in the books which say
But, you will see from your code in you actionPerformed method that that example doesn't work for everything. What you actually want is an ActionListener which is different for each of the actions. You have three different possibilities for adding action listeners, which are, No 1:There you have to put in the source for what you want it to do. This is really suitable for when you have several parts of the present window which you want to do similar things.
No 2:What you are doing is writing a class for each action you want, then you can use it once or several times, and you might wish to vary the activity; you can pass parameters to the ActionListener, like this:
In your 2nd example, look what you are passing as an ActionListener, and look what you have called your ActionListener. That might explain what has gone wrong.
I think you want an AddActionListener class, a ResetActionListener class and an ExitActionListener class, and they are probably easiest to use set up as inner classes.

No 3: The anonymous inner class. This is suitable for situations where you have one component which carries out one action, and that appears to be what you have here.

This is how I write them, which gets me out of remembering how many {} and () to use:
Stage 1:It won't work yet.
Stage 2: Put your mouse inside the () parentheses or round brackets and "break" the line by putting two "enter" keystrokes in it. It should now look like this:
Stage 3: Put your cursor in the gap and write the following: new ActionListener(){}. You should now have this:
Stage 4: Put more newlines and indents in to get the braces into the right position, like this:
You now have the bounds of your class, and
Stage 5: inserting public void actionPerformed(ActionEvent e){}, and re-indenting, gives you this:

Stage 6: Write the body of your method.
I think you are best to bite the bullet of anonymous classes, try them one at a time, and see what you make of them.
CR

[ November 26, 2005: Message edited by: Campbell Ritchie ]
benny rusli
Ranch Hand

Joined: Jan 15, 2005
Posts: 72
Hello people,

thanks for responding my questiong. But what i want, is to split my code into mvc design pattern, not using the anonymous inner class or the other method.

[Campbell Ritchie]: this is one of what you meant, using the anonymous inner class. But this is not in MVC Pattern or ? If i use mvc concept, i should separate the event handling in another new class as model, the view and controller is Swing normally they say ComponentUI/Delegate. Any further information or help would be appreciated.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38519
    
  23
Thank you.

So far, so good. You have got your anonymous inner classes working AOK, and your app will compile and run nicely. It adds up properly, but you need to add a statement on the lines of to your "reset" handling.

I don't see that anonymous inner classes violate the MVC design; they are part of the "C."

You are still making like too complicated for yourself.
Each inner class can be different from all the others; each is only asociated with one button; each only needs to implement the single action associated with that particular button.
So you can miss out thebit. The ActionListener you associate with your exitButton (BTW: call it exitButton or endButton or buttonExit, not b1 or b2) only has to implement the single line which exits your app. Remember, you have added the ActionListener to the button, not the whole Frame.

So you can simplify it to

If you prefer to have separate classes, you would have an ExitActionListener class, which as a private inner class would read more or less the same as above:-
I think a private inner class has to be entirely enclosed within the {} delimiting the class it lives inside, but am not quite sure.
Of course for "exit" you could put the class in a file of its own, declare it public, and reuse it for your next GUI exercise.


The "add" button (or a KeyListener for the input text field, which can share a method with the add button) and the reset button ActionListeners can be worked out similarly.
You only need the exception handling in the "add" and key listeners.
[ November 26, 2005: Message edited by: Campbell Ritchie ]
benny rusli
Ranch Hand

Joined: Jan 15, 2005
Posts: 72
hello people,

thanks again for responding my question, thanks for remembering me about this features, you have teached me to use a different kind of placing event handling such as private/public inner class (separate classes), the anonymous inner class, the using of this keyword(refence to method actionPerformed()) which i have used in my first example. But now my question, when should i use public inner class and when should i use the anonymous inner class, because the both method is suitable for situations where we have one component which carries out one action (This is really suitable for when we have several parts of the present window which we want to do similar things.). The second question, i think the difficult one, what will happen if i want another View like the layout is BorderLayout or GridBagLayout not FlowLayout but the same action event (reset,exit,and add the value). Of course i should make it new the whole code and change the Layout Manager with setLayout() method, this is what i dont want, this is not reusable. So maybe my question a little bit confusing you, i hope you understand what i meant. Any further information and help would be appreciated. I have changed the code according your suggestion, here is the actual one :


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38519
    
  23
Thank you.
We try to help.
You can leave out the bits likebecause the ActionListener is specifically added to that button, so e only has one source.
You can either use private inner class (not usually public) or anonymous classes if you have one soure giving rise to one action.
If you have several sources giving rise to the same action (eg an exit button and exit in your menu), you use the private inner class, then both the items can have an ExitListener added.

The nice thing about object-oriented programming is that you can alter one class, your display ("V"), and it doesn't alter the other classes (your ActionListeners are all objects which are instances of classes derived from the ActionListener interface, whether you give them a name or not, whihc are "C").
Or: you can change the layout, in "V" to anything you want, and it won't make the slightest difference to your ActionListeners.

BTW: I tried the KeyListener on your app last night, and for some peculiar reason which I didn't bother to work out it only worked when I implemented the keyReleased method, not the keyTyped method.
Anybody else know why?

CR
benny rusli
Ranch Hand

Joined: Jan 15, 2005
Posts: 72
Hello people,

i have corrected some mistake that i have done in my code.

[Campbell Ritchie]: i have tried in another program for the KeyListener and it worked out. Here is the example code :



[BTW: what do you want with the KeyListener ? Do you want to change ActionListener to KeyListener ? therefore you use KeyListener or what]


and here is the new corrected one from the MainFrameGUI.java, do you know why if i use static int sumresult = 0; replacing for int sumresult = 0; giving the same result. What and where is the different from non-static (instance variable) and static variable, in this case is no difference between both or ?. Thanks for the feedback.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38519
    
  23
Thank you.

What I meant was that, if you have a KeyListener listening for the enter key, the same VK_ENTER, then you can use either the "add" button, or a keystroke on the enter key in the entry box, as you have got to work elsewhere. You don't have to; it is just a possible alternative. You have achieved a better approach to the text field than what I suggested, [ ] where the action listener reacts to the enter key.

BTW: If you do have a KeyListener in the app you are describing, beware of implementing all three methods, otherwise there is a risk that you will add the number in the text field three times. :roll:

I think you ought not to use the static int variable; if you ever instantiate two objects of your MainFrameGUI class, they will both have the same resultsum variable. You would get some surprising results; try it and see what happens.

You don't need the bit about if(e.getSource() == exitButton) . . . You have added one ActionListener to each of the three activated components; each component has one listener, and each listener has one source. So if you get an event to the exitButton listener, it can only come from the one source, the endButton. So if(e.getSource() == exitButton) is always true, and therefore there is no need for that line. You can just writeAnd we are only too pleased to be of help.
[ November 28, 2005: Message edited by: Campbell Ritchie ]
benny rusli
Ranch Hand

Joined: Jan 15, 2005
Posts: 72
Hello people,

do we make a progression in the program ? you have a great basic [Campbell Ritchie], you know when to use the anonymous or public/private inner class. Reffering to KeyListener, i will try it later to implement all the method. I still dont understand when to use the static variable and when to use non-static variable, the static variable is associated with the class as a whole and the non-static variable is associated with the instance of the class. We can say that non-static variable is a dynamic variable means that each object or instance have or can have a different value. Normally they use the static variable for the constant like in the package java.lang.Math such as PI, etc. Until now i use only non-static variable and implement only with non-static variable therefore i dont understand practically the difference. About the listener and source, each component has one listener, and each listener has one source, so i modify it again the code. You meant that if i use one listener for three component, i should/can use if(e.getSource() == exitButton). Here is exactelly what you meant :

Here is the example using one listener for three source(component):



Here is the example using three listener for three source(component):


Here is the actual right one :


is there another alternative that i forget ? any further information would be appreciated. Nice for the cooperation and your helping.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38519
    
  23
Flattery like that will get you anywhere.

I would suggest you add a line to your action listeners to delete the text in the text field, and leave the zero out of the JTextField() constructor call. Otherwise if you put 1 in you and don't push delete you actually get 10. I think you have got your app working exactly as you want it. Well done.

I wouldn't set the sumresult as static. I have suggested already you try setting it static, then instantiating two frames. Try it. Putin your main method. See what happens when your sumresult variable is static, and what happens when it is an instance variable (non-static).
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: how to implement mvc or observer pattern on this java code ?