Monday, January 18, 2010

How to use command line arguments from a basic Netbeans gui project

For some reason, it was really hard to figure out how to achieve this. The problem I was getting was " non-static variable this cannot be referenced from a static context ". Now that I know what I was doing wrong, it all makes perfect sense, but at the time it didn't. So here's a tutorial for all of you other java noobs like me that want to take the shortcut to a working application fast without completely undestanding java :)


/*
* DesktopApplication1.java
*/

package desktopapplication1;

import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;

/**
* The main class of the application.
*/
public class DesktopApplication1 extends SingleFrameApplication {

//Something to hold the new argument
private static String myargument;

//method to get the argument
public String getArgument() {
return DesktopApplication1.myargument
}

/**
* At startup create and show the main frame of the application.
*/
@Override protected void startup() {
show(new DesktopApplication1View(this));
}

/**
* This method is to initialize the specified window by injecting resources.
* Windows shown in our application come fully initialized from the GUI
* builder, so this additional configuration is not needed.
*/
@Override protected void configureWindow(java.awt.Window root) {
}

/**
* A convenient static getter for the application instance.
* @return the instance of DesktopApplication1
*/
public static DesktopApplication1 getApplication() {
return Application.getInstance(DesktopApplication1.class);
}

/**
* Main method launching the application.
*/
public static void main(String[] args) {

DesktopApplication1.myargument = args[0];

launch(DesktopApplication1.class, args);

}
}


So you save the argument to a static variable using class reference and create a method to retrieve the value (private static String myargument; and public String getArgument() ) Then from the applications main frame you can now call that method once you have changed the constructor a bit (public DesktopApplication1View(DesktopApplication1 app) ).


/**
* The application's main frame.
*/
public class DesktopApplication1View extends FrameView {

public DesktopApplication1View(DesktopApplication1 app) {
super(app);
//Use the argument
System.out.println(app.getArgument);
initComponents();


I know this might not be the optimal solution, but it works. Sometime you just need to create a quick java app without learning the whole language. An app with a basic netbeans guin and some command-line arguments :)

1 comment:

  1. You can override the Application.initialize method which has the arguments passed as the argument. This is in the non-static portion of the code and is executed before the startup() method.

    ReplyDelete