Thursday, September 30, 2004

Changing name of Popup menu item based on a variable

The name of the menu item in the popup menu depends on the NAME attribute of AbstractAction of that menu item.

When you add some subclass of AbstractAction to the JPopupMenu, you can specify any name to be displayed in the menu by calling super.putValue(NAME, "yourname");

Shown below is an implementation of AbstractAction that does it in the constructor.

public class AddAction extends AbstractAction {

public AddAction(int type)
{
super("Add");

this.type = type;

if(type == 0)
super.putValue(NAME,"Type 0");
else
super.putValue(NAME,"Type 1");
}
}


and add it to the popup menu as follows


JPopupMenu popup = new JPopupMenu();

popup.add(new AddAction(0));
popup.add(new AddAction(1));

here I have added 2 menu items using the same Action but with different names. YOu can ofcourse take different actions based on which menu item is clicked by checking the type in AddAction.


Tuesday, September 28, 2004

Make a Swing component not take up all the space

Most common frustration when designing with Layouts is that your nice pretty layout gets all screwed up because the container panel blows up to take up all the space. Even if you try a setPreferred or setMaximumSize , it seems to have no effect.

A common trick I do to avoid that is to use a wrapperPanel with its layout manager as BorderLayout. and I dump the container panel in the NORTH area of the wrapperPanel.
How BorderLayout works is that, it allocates components in the border's their preferred sizes, and all the rest of the space is filled up by CENTER. So now by adding it to NORTH, the container panel's preferred sizes come in to play, and all left over space is gobbled up by CENTER.

--
When you have a similar problem with the other components, like buttons, text boxes etc, I prefer to use GridbagLayout which automatically assigns the space equivalent to the components preferred sizes. and using GridBagConstraints you can use insets and margins, to your hearts content to layout the components perfectly. Once you understand it , GridBagLayout kicks ass.

With JTree's or I think anything that is within a JScrollPane, adjusting the preferred size of the inner component doesnt have any effect. Adjust the preferred size of the scrollpane to achieve the desired effect.

See Swing, Second Edition by Matthew Robinson, Pavel Vorobiev, published by Manning for a good explanation of GridBagLayout.






Wednesday, September 01, 2004

Accessing a file relative to the class file location

BufferedReader bufferedreader =
new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("filename.txt")));

---------------------
Here filename.txt is assumed to exist in the same directory as the class file.
---------------
gate : edu.upmc.oip.utils.client.dialog.NCIMetaTreeViewerDialog