Thursday, December 20, 2007

Eclipse RCP, add new wizard to the workbench File menu and toolbar at the root level

Here is how you add your wizard as an option under the File > New menu, and toolbar drop down button.

If you were like me, you should have been easily be able to add a new wizard, but when you added it to the file menu, it added your wizard under the Others... category.

Here is how you get it at the root level, i.e. the same level as the new File and Folder wizards.


Step 1: Add the newWizards extension and your new wizard under it.
Step 2: Add the perspectivesExtensions extension and a newWizardShortcut extension under it.

Here is how the plugin.xml looks:

<plugin>

<extension id="application" point="org.eclipse.core.runtime.applications">
<application>
<run class="edu.pitt.dbmi.odie.Application">
</run>
</application>
</extension>
<extension point="org.eclipse.ui.perspectives">
<perspective name="RCP Perspective" class="edu.pitt.dbmi.odie.Perspective" id="edu.pitt.dbmi.odie.perspective">
</perspective>
</extension>
<extension point="org.eclipse.ui.newWizards">
<wizard class="edu.pitt.dbmi.odie.NewDocumentCollectionWizard"
id="edu.pitt.dbmi.odie.NewDocumentCollectionWizard"
name="Document Collection">
</wizard>
</extension>
<extension point="org.eclipse.ui.perspectiveExtensions">
<perspectiveExtension targetID="edu.pitt.dbmi.odie.perspective">
<newWizardShortcut id="edu.pitt.dbmi.odie.NewDocumentCollectionWizard">
</newWizardShortcut>
</perspectiveExtension>
</extension>

</plugin>


Step 3: create the actions and add it to the menu and toolbar.
You can edit the ApplicationActionBarAdvisor.java. You will need to override the makeActions, fillMenuBar and fillCoolBar methods.

Here are how they look:

IWorkbenchAction quitAction;
private IWorkbenchAction newWizardDropDownAction;
private IContributionItem newWizardMenu;
public ApplicationActionBarAdvisor(IActionBarConfigurer configurer) {
super(configurer);
}


protected void makeActions(IWorkbenchWindow window) {
newWizardDropDownAction = ActionFactory.NEW_WIZARD_DROP_DOWN.create(window);
register(newWizardDropDownAction);

newWizardMenu = ContributionItemFactory.NEW_WIZARD_SHORTLIST.create(window);
}

protected void fillMenuBar(IMenuManager menuBar) {


MenuManager menu = new MenuManager("File", IWorkbenchActionConstants.M_FILE);

{
// create the New submenu, using the same id for it as the New action
MenuManager newMenu = new MenuManager("New", "new");
newMenu.add(this.newWizardMenu);
menu.add(newMenu);
}

menuBar.add(menu);

}

@Override
protected void fillCoolBar(ICoolBarManager coolBar) {
ToolBarManager toolbar = new ToolBarManager(SWT.FLAT);
toolbar.add(newWizardDropDownAction);

coolBar.add(toolbar);
}


Note, Step 2 can also be done in code. Just add this line to the createInitialLayout method of your perspective

public void createInitialLayout(IPageLayout layout) {
layout.addNewWizardShortcut("edu.pitt.dbmi.odie.NewDocumentCollectionWizard");
}

IMPORTANT: Donot forget to clear workspace data to see your changes.

Monday, January 16, 2006

How to detect changes in a JTextField

textField.getDocument().addDocumentListener(new DocumentListener(){

public void changedUpdate(DocumentEvent arg0) {
}


public void insertUpdate(DocumentEvent arg0) {

}

public void removeUpdate(DocumentEvent arg0) {
}

});

Wednesday, March 02, 2005

Calculating execution time of a block of code

org.apache.xindice.Stopwatch has a nice stopwatch

Wednesday, January 19, 2005

convert String to InputStream

byte[] bytes = str.getBytes();

ByteArrayInputStream bais = new ByteArrayInputStream(bytes);

Thursday, January 13, 2005

How to have a page start from the top of the browser window, and occupy entire height of the browser

Using XTHML and CSS:

html, body {
height: 100%;
margin: 0;
padding: 0;
}
table {
height: 100%;
width: 100%;
background-color: #CCC;
}

avoid JDialog from being hidden when user switches to another application window

Common frustration with Java. Your child dialogs seem to disappear if you switch to another application window and come back. The only way to switch to the dialog box seems to be thru the task switching function ( Alt+Tab )


Actually, that only happens when you pass null to the constructor of JDialog. If you pass the parent frame's reference to the JDialog constructor, the jdialog is automatically made visibile when the user returns to your application.

Tuesday, January 11, 2005

Setting cursor for entire application

The secret is that you have to change the cursor on theoriginating component AND on its frame!Here's a little code snippet (part of a static utility class) that does the job :

public class Util {

public static void doWaitCursor (Component component) {
setCursor(Cursor.WAIT_CURSOR, component);
}

public static void noWaitCursor (Component component) {
setCursor(Cursor.DEFAULT_CURSOR, component);
}

public static void setCursor (int cursor, Component component) {
component.setCursor(Cursor.getPredefinedCursor(cursor));
Frame frame = getFrame(component);
if (frame != null)
frame.setCursor(Cursor.getPredefinedCursor(cursor));
}

public static Frame getFrame (Component c) {
if (c instanceof Frame)
return (Frame) c;
while ((c = c.getParent()) != null)
if (c instanceof Frame)
return (Frame) c;

return null;
}
}

Source: http://forum.java.sun.com/thread.jspa?threadID=111793&messageID=296338

Wednesday, December 15, 2004

Sending and receiving objects over an HTTP connection

public static Object sendObject(Object obj) {
URLConnection conn = null;
Object reply = null;
try {
// open URL connection
conn = servletURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches( false );
// send object
ObjectOutputStream objOut = new ObjectOutputStream(
conn.getOutputStream() );
objOut.writeObject( obj );
objOut.flush();
objOut.close();
} catch ( IOException ex ) {
ex.printStackTrace();
return null;
}
// recieve reply
try{
ObjectInputStream objIn = new ObjectInputStream(
conn.getInputStream() );
reply = objIn.readObject();
objIn.close();
} catch ( Exception ex ) {
// it is ok if we get an exception here
// that means that there is no object being returned
if( !(ex instanceof EOFException))
ex.printStackTrace();
//System.err.println("*");
}
return reply;
}

ref: edu.upmc.opi.caBIG.caTIES.client.vr.utils.ncimetasearch.NCIMetaSearchComponent

On the servlet side :

ObjectInputStream objIn = new ObjectInputStream(req.getInputStream()); try { Object obj = objIn.readObject();

ref: edu.upmc.opi.caBIG.caTIES.server.mmtx.MMTxService

Wednesday, November 03, 2004

handling xml from string

u need jaxp.jar for this.

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

Document xmldoc = builder.parse(new ByteArrayInputStream(xml.getBytes()));

Monday, November 01, 2004

Signing your jar files

This is required when you want to deploy your application using webstart.

First step is to have a keystore. The following page describes how to create a self certified keystore.

http://mindprod.com/jgloss/keytool.html

--then you have to use the jarsigner tool

jarsigner -keystore targetFile.jar alias

See the mindprod page for full details

Tuesday, October 05, 2004

Of files and filepaths in Java

This is a major stumbling block for me every time. As I learn new methods I will keep updating .

For now here is the simplest :

FileReader f = new FileReader("tmp.txt");

Now where the hell do u place tmp.txt, you might ask. Well, to find where Java tries to look for tmp.txt, do this

System.out.println(System.getProperty("user.dir");

To open a file relative to the class file location is something that would really help. And it is supposed to work by using class.getClassLoader().getResourceAsStream(), but it didnt work for me, will post as soon as I know how it works.




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

Monday, August 23, 2004

super() in Java

Dude,

super() has to be the first line in any function you use it in. Period. End of Discussion.

Wednesday, August 18, 2004

Tokenize strings, the StringTokenizer

Notice the different techniques to use tokenizer. StringTokenizer is self - explanatory,
RETokenizer tokenizes on regexs. The one in the example, treats and, AND, or and OR as
delims and also returns the delims as tokens. StringTokenizer doesnot return delims.

----------------------------------------------------------------------------------
String text;
StringTokenizer st = new StringTokenizer(text,",");
-----------
Iterator t = new RETokenizer(s,"\\s(and|AND|or|OR)\\s", returnDelims);
while(t.hasNext())
{
String cs = (String)t.next();

if(!(cs.equalsIgnoreCase(" and ") || cs.equalsIgnoreCase(" or ")))
conditionList.add(cs);
}
----------------------------------------------------------------------------------
ProtocolQuery : edu.upmc.database.SQLStatement

Server Side includes when your server doesnot support it

This works only with HTML. A typical use will be to place some piece of html code at the top of every page on the website, used when you have a menu bar on each page. A big pain is to modify the menu, because you have to go to each and every page and do the changes to make it uniform.

Ofcourse there are other solutions like using frames so that now there is only 1 file to modify.

But what if you dont want to use frames.... Javascript to the rescue.

Use Javascript document.write method to write out the html code to your page. Place this javascript code in a something.js file and include something.js in every page where you want to have that html code present.

Including for javascript is as simple as
<script language="javascript" src="something.js">

I typically write 2 functions in this file, namely writeHeader() and writeFooter(). At the exact location where I want the code to be written I call this function

Example :
<body class="main" onload="MM_preloadImages('images/mmenuhomeon.gif','images/mmenuabouton.gif','images/mmenueventson.gif','images/mmenugovernon.gif','images/mmenubbon.gif','images/mmenulinkson.gif','images/mmenucontactoff.gif')">

<script type="text/javascript">writeHeader()script>

<table width="100%" cellspacing="0" cellpadding="0">
<tr>
...
...
-----------------------------------------------------------------




Of ActionListeners and Popup menus

An example of how to use ActionListeners.
-------------------------------------------

class LoadAction extends AbstractAction {
LoadAction(){
super("Load"); //this is the menu item name in a popup

}

public void actionPerformed(ActionEvent e){
//do what you want to here
}

---------------
JPopupMenu popup = new JPopupMenu();
popup.add(new LoadAction());
---------------

You can also call the Action explicitly by

new LoadAction().actionPerformed(null);

-----

If you need access to members of the parent class pass them to the LoadAction constructor. when you create it.
--------
edu.upmc.opi.spin.client.SpinDataStoreTreeViewer



About this blog

Hi wanderer,

This blog wasnt created for your viewing pleasure. It just contains some random ideas and code snippets that I come across when I am at work. I need a place to store these so that I can get back to them when I need them. So if some posts dont make sense to you at all... well... they weren't meant to.