Help coderanch get a
new server
by contributing to the fundraiser

Ashish Mahajan

Ranch Hand
+ Follow
since Feb 19, 2003
Merit badge: grant badges
For More
Cows and Likes
Total received
In last 30 days
Total given
Total received
Received in last 30 days
Total given
Given in last 30 days
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Ashish Mahajan

Hi Dave and Avi,

There's no need to fight though

Just wanna say that nobody here is fighting. I have seen the guys here r really and helping. The problem is the channel thru which we r trying to communicate. Here we can't see each other's faces, expressions, mood etc.. Had Avi and I been sitting together I would not even had 2 sign off as Sincerely. However this is still the best (cause it's the cheapest available) medium.
Best Wishes,
21 years ago
Hi Gregg,
Sorry 4 late reply. Was relaxing a bit. I was not clear last time. This time i will try 2 b clear.

So is the Observable pattern that you mention something that has to be used explicitly along with Action Patterns? Or does Action Patterns subclass or implement Observable patterns and you can just use them that way?

I will just say few stuff. One can say, Observer == listener pattern. In short, if one uses Listeners in coding then we can say that he has used "Observer" pattern. When we design systems, we distribute the responsibilities among different classes like Managers, general clasees, Utility classes, etc.. and expect that they will on their own communicate with each other thru event notification mechanism. (And we r dammn sure about their behaviour cause they r not bloody egoist humans.) Now the classes which provide service (can be any class) should notify interested clients thru event notification. AbstractAction does this thru foll. API :-
1. addPropertyChangeListener(PropertyChangeListener)
2. removePropertyChangeListener(PropertyChangeListener)
and other related methods like getPropertyChangeListeners
When we pass Action to JButton or JMenu it calls it's setAction method which adds a property change listener if not added and configures it's properties according to the passed in action. (See the src code)
AbstractAction has getValue() putValue() methods. If any client puts any property (can be a standard defined in Action interface or any custom property) by putValue() then the AbstractAction fires a property describing that key-value. Now the resgietsred clients r the buttons and menu items or any other components like status bar fields. They quickly update their properties from the propertyChangeEvent. The code to do this is naturally in parent AbstractButton class. This class updates itself for the known properties defined in Action interface (like NAME, SMALL_ICON, etc..). So is achieved synchronization. One point to b noted is that :- Although the synchronization of buttons and menu items properties is automatic for the developer (cause Sun guys have done it 4 us in AbstractButton) there can be other components where the actions should be used e.g. Status bar field. In status bar any action can come cause the user can customize the status bar components thru customization if provided. So it's better to write StatusBarField component which will have almost API like AbstractButton like constructor accepting Action (same as JButton or menu item), setAction, and configurePropertiesFromAction etc.. Also not all the status bar fields should accept Action e.g. the field used for displying description has nothing 2 do with Actions. So the designer should design accordingly.

I have read on Observable patterns before, the problem is that all the examples I see don't introduce examples like you stated. So it is hard for me to take them over to a SWING example.

Actually i haven't read such examples from any book. I just try to study the existing designs in general life as well as in computing. There r lots of interesting examples. e.g. regarding the computing design. One more example about the "Observer" pattern would be Client-server chat. Instead of two clients constantly asking the server whether there is any message from other chatters (and many a times get upset) while the chatter logs in it should register with the server and any chatter just sends message to sever and that server will have handles of all the chatters and will notify all the other chatters. I have heard from my friend that some messangers constantly (in while(true) loop) queries server about other chatter's message etc. God bless such designers
About the example in general life. U know i never give my company's mail id to anybody (or if i give i also give one more default mail id as fallback) the reason being that by doing so i am exposing the internal details i.e. the company name (not following the "data encapsulation" design principle) . When i will join other company all my friends now will have to update their Address book just because i have joined a new company. Had that mail id from say yahoo then that will work till the rest of my life.

If you know of a simple SWING example that implements that patterns you described, could you provide me a link?

I don;t have any links. But i will HIGHLY RECOMMEND the Core JFC by Kim Topley. This is the best book on swing. The author has more than 30 yrs experience in GUI building/designing. Study carefully how he approaches the solution of any prob. He approach is the best, slowly by slowly step by step.
Best Wishes,
21 years ago
Hi Avi,
Thanx for the link. But i'll still go for XDialog than the example in the article the reasons being :-
1. If any text component is placed in the example dialog (and it has focus) then it won't dispose cause the key stroke won't travel up the container hierarchy to reach JRootPane but will be handled by the text component.
2. XDialog adds another functionality of removing selection in the text component if that text component is in frame.
3. The example uses although not deprecated but obselete API namely registerKeyboardAction(ActionListener, KeyStroke, condition). I think the article is written prior to JDK 1.3. In JDK 1.3 Sun guys have introduced an excellent architechture for handling keystrokes. namely getInputMap() and getActionMap(). The obsolete registerKeyboardAction() method hardcodes the key strokes. Since keystrokes/key bindings r LookAndFeel dependent, one should not use that method rather use combination of getInputMap() and getActionMap() which provides a loose coupling between keystrokes and the target action. In short the LookAndFeel should define the inputmap with key as keystroke and a command as value and that command will be used as a key to look up for the action in the action map.
However NOTE that the XDialog still hardcodes the key stroke (ESC) bacause the functionality desired by "ESC" key pressed is same for all the LookAndFeels i.e. disposing the dialog.
So to practice better API, and the reasons stated above i'll still go for XDialog.
21 years ago
Hi Gregg,
Let me bore ya more on the power of using Actions cause perhaps i won;t be around much from 2Morrow in the favour of server side computing.
Although in the pattern books u'll get the power of Actions as supporting undo-redo operations, decoupling the object that invokes the operation from the one that knows how to perform it etc..., swing's Action is an example of another perhaps the most powerful pattern, "Observer" pattern.
I can't imagine programming without "Observer" pattern. All the listener stuff are the example of "Observer" pattern. The power comes form the fact that the client (Observer) doesn't have to watch other constantly for any result. It can carry on with it's work and when something interesting happens the Observable (publisher) notifies the client (Subscriber) about the change with necessary info so that the client can update itself.
To recognise this power in general life - U know right now am searching for a server side job. I have registered to lot of job related sites. Now instead of checking those sites after every XXX time to check whether there r any mathced jobs or not (and many a times not getting any result) is really wastage of valuable time and is also painful to me. Instead of this if the job sites automatically delivers mathed jobs directly to my mail box (event notification) that way i can carry on my day to day work (no need to check job sites every now and then).
In programming scenario :- Let's assume that we r designing a text editor. Now any action can appear at any places say a menu item, a tool bar button or status bar field, or may be other custom comp or any other comp that may come in future. We need to always make sure that the staes of different component representing the same action should be same at any time. E.g. a ReadOnlyAction. The text editor can be set to read only mode from say menu item or the opended file itself can be a Read only. Now as soon as the editor becomes readonly all the component's (representing readonly action) icon's should be changed to represent the ReadOn-ReadOff state. Now if we don;t use Actions here then we will have to make sure that all the necessary component's icons remains synchronized at any time manually. A typical project has over hundread actions. It will be developer's nightmare to always make sure that the states r synchronized. Instead if we use Actions then all the synchronization will be automatic. A ReadOnlyAction in it's init method will add a property change listener (again "Observer" patterns) to the application frame's editor for namely "editable" property and will set it's icon according to the editor's state. After putting the SMALL_ICON property value in ReadOnlyAction all the components representing it will automatically update their icons.
Another example would be to enable/disable certain actions upon the document loaded/unloaded.
This is really powerful.
Thanx for bearing me.
21 years ago
Hi Gregg,
Am a very fond of Design Patterns and use it heavily while designing and coding. U may be knowing but still let me list few Design patterns book all these books include "Command" Pattern. Actually javax.swing.Action is also an example of another pattern namely "Observer" pattern.
1. The famous GoF (Gang of Four) Design Patterns book the best book of the last decade. Although they have used SmallTalk and C++ but still the best book on patterns.
2. [URL=]Patterns in Java Vol. 1 by Mark Grand[/URL] Best Book. The author is one of my most favourite
3. Patterns in Java Vol. 2 by Mark Grand
4. Java Design patterns a tutorial by James Cooper Sorry i didn't like this much. I expected a lot but it's just normal book not a cracking. This book uses Java and UML so it may be of help also.
Well there other good books also.
For a complete list of design patterns info, visit
21 years ago
Hi Mario,
Glad 2 hear that u r using Actions.
Actually this won;t solve the probs u mentioned but just for a note :-
Am assuming that a unique action is shared by all the interested components. In short new actions r not created for both tool bar button and menu item. For this, the application frame should keep registry map of action name to it's action and clients (software components) should query for any action by name
OK back to point :-
Actually this should not happen. What happens internally is - since action is shared by say menu item, tool bar component, status bar field, etc. when we put any property in Action it fires property to all it's interested clients (menu items and buttons in their constructors regiters themselves as property change listeners to passed in action) After putting SHORT_DESCRIPTION in the tool bar, a property with the same name is fired and the intersted clients resets their properties e.g. JButton will reset it's tool tip in this case.
If it's not happening as expected then simply at the place where u r creating tool bar button set it's tool tip explicitly by setTooltipText(String) method with the text got from corrosponding action's SHORT_DESCRIPTION. That should solve ur prob
Actually the ans. would have been in one line, but i just thought to bore U.
21 years ago
Hi Brandon,
instead of adding keyListener to the spinner, add key listener to it's editor's text field like this :-


where spi_price is a spinner. At a first glance the type cast may seem as unsafe. Actually spinner's editor type is JComponent but since u r setting the editor and if ur organisation decides that the standard editors provided by Sun r sufficient and that if any custom spinner editor is to be developed in ur org. will extend the default editor then such type casts r safe.
21 years ago
Hi Rahul,
First of all, don't be 2222 formal. All here r friends sharing thoughts & ideas.
Instead of spoon feeding, i'll rather give u some hints :-
1. Read java.text.BreakIterator javadocs
2. Take a look at Text Bound Demo
3. If u r not going for BreakIterator stuff then :-
After getting text of the document get it's char array and traverse back and forth to find the word boundaries. NOTE consider i18n issues and instead of checking for " " (space character) check whether the given character is space or not by Character.isWhiteSpace(char) method.
Note that the default BreakIterator instance assumes word boundary at every non letter and digit so there is high possibility that u may go for No. 3 option. NOTE that BreakIterator can be customized to suit any requirement.
Hope this will give u some dirn.
21 years ago
Hi Ransika,
I just wanna add my $0.02
What Chad said is right. But Sun guys have made our life easier by providing setDefaultButton(JButton) method in JRootPane. One reason why one would opt for setting default button is that - On Mac OS X the root pane's default button glows beautifully like a heart beat.
One point to be noted in this connection. JDK 1.3 has a bug in that if user is navigating the application menus with key board and presses "Enter" expecting that menu item's action getting fired but the default button's action gets fired. However they have fixed this bug in 1.4.
If u r developing for Mac OS X also then u may be worried about this 1.3 bug. Possible solution is to write a sublcass of JMenu say XMenu in it's init method add a MenuListener and in it's menuSelected(MenuEvent) method after taking a backup of default button set root pane's default button to null and in deselected method restore the default button.
21 years ago
Hi All,
One more thing to note is that the text component's "key binding" is LookAndFeel dependent. but while designing i have assumed that disposing when "ESC" is pressed is desired in all LAFs.
If anybody wanna give different "ESC" actions for different LAFs then one should write a code to listen to "lookAndFeel" property from UIManager in static block and add/remove keystrokes from the shared text component's key map. Like addActionKeyStroke(KeyStroke, Action) method, the interface Keymap also has removeKeyStrokeBinding(KeyStroke) method
21 years ago
Hi All,
Please ignore above ugly solution suggested by me few days back.
I was figuring out a proper, standard solution to this common required functionality - disposing the dialog with "ESC".
The requirement was :- All the dialogs should be able to dispose with the "ESC" key pressed. There should not be a need to add key listener to every text component for disposing the dialog.
While doing this i found one missing functionality in text components. If there is any selection is text component and "ESC" is pressed then it should remove this selection. Since every dialog should be disposed at "ESC" even if the text component inside it has focus, then i added one more extended requirement :- If the text component is in dialog then that dialog should be disposed and if that text component is in frame then it should remove selection if there is any when "ESC" is pressed. (naturally we don;t want frame to be disposed at "ESC"). I got a green signal when i found that popular text editors like "TextPad" behaves in the same way.
So here is the revised code of XDialog :-

public class XDialog extends JDialog
// All the constructors go here
// and all the constructors after calling super's version calls initXDialog method
// -- static block
// Add Escape key binding to the shared JTextComponent key bindings so that if any
// text component is inside Dialog then dispose that dialog
KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke((char)KeyEvent.VK_ESCAPE);
Keymap map = JTextComponent.getKeymap(JTextComponent.DEFAULT_KEYMAP);
map.addActionForKeyStroke(cancelKeyStroke, cancelKeyAction);
private static Action cancelKeyAction = new AbstractAction()
public void actionPerformed(ActionEvent ae)
Component comp = (Component) ae.getSource();
Window window = SwingUtilities.windowForComponent(comp);
if(window instanceof Dialog){
else if(comp instanceof JTextComponent && ! (comp instanceof JFormattedTextField)){
JTextComponent tc = (JTextComponent) comp;
int end = tc.getSelectionEnd();
if(tc.getSelectionStart() != end){
* Method for initialization.
* This implementation adds a window listener to dispose itself while closing
* This also adds functionality of disposing if "ESCAPE" is pressed
private void initXDialog()
KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke((char)KeyEvent.VK_ESCAPE);
InputMap inputMap = getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actionMap = getRootPane().getActionMap();
if(inputMap != null && actionMap != null){
inputMap.put(cancelKeyStroke, "cancel");
actionMap.put("cancel", cancelKeyAction);
} // end of class XDialog

But one more thing i observed that Formatted text field should be behaved in a different way in that when "ESC" is pressed in formatted text field it's valid value should be set and that means even if formatted text field is in dialog that dialog should not be disposed. Since the solution involves modifying a shared (static) key map of JTextComponent that means for every JFormattedTextField we create we should override the parent key map to provide a default "ESC" functionality. So it's better to subclass JFormattedTextField say XFormattedTextField which has foll code in it's init :-

KeyStroke cancelKeyStroke = KeyStroke.getKeyStroke((char)KeyEvent.VK_ESCAPE);
JTextComponent.KeyBinding[] bindings = new JTextComponent.KeyBinding[]{ new JTextComponent.KeyBinding(cancelKeyStroke, "reset-field-edit") };
JTextComponent.loadKeymap(getKeymap(), bindings, getActions());

NOTE that the individual requirement can vary.
Hope this helps.
21 years ago
Sorry, This is not the ans. to the ques.
Ali, the html file for swing namely (home1.htm) contains a serious virus.
Here is what i get from Norton Antivirus :-
Object Name : C:\Documents and Administrator\Locale settings\..\home1[1].htm
Virus Name :HTML.Redlof.A
Action Taken :Unable to repair this file
upon searching the net for virus i get the foll link :-
Ali, if u r lurking here, let us know that u have read this post and that u r going to remove the virus immediately. If we don;t get reply from u, we will post in a separate thread. I don;t want any of my friend's comp being crashed.
I hope u will take immediate action.
21 years ago
Hi Vishal,
I dunno anything about J2EE. So am backing off. But am very pleased that u have given a thought of considering J2EE tech. At the same time am jealous of u, now-a-days am seriously considering doing serious server side project.
It's better to spawn a separate thread in J2EE forum.
May be Nathan can best guide u.
21 years ago
Hi Vishal,
Don't u think this is a very good opportunity to master J2EE technologies.
21 years ago
Hi Sonara,

int location = textPane.viewToModel(point);
// From this location in model one can easily find the word/text at that position

Hope this solves ur probs
21 years ago