Last Updated on 07 August 2019   |   Print Email
In this Eclipse and Java tutorial, we show you the steps to pass arguments when running a Java program. Suppose that we have a program which can be executed in two modes console and GUI. Here’s its code:
package net.codejava;
/**
*
* @author www.codejava.net
*
*/
public class MyApp {
public static void main(String[] args) {
if (args.length < 1) {
throw new IllegalArgumentException("Please specify mode: console or gui");
}
String mode = args[0];
if ("console".equals(mode)) {
new ConsoleApp();
} else if ("gui".equals(mode)) {
new SwingApp().setVisible(true);
}
}
}
This program accepts one argument. If it is “console”, a console version will be invoked:
package net.codejava;
/**
*
* @author www.codejava.net
*
*/
public class ConsoleApp {
public ConsoleApp() {
System.out.println("Hello, this is a console app.");
}
}
Or if the argument is “gui”, a Swing GUI version will be invoked:
package net.codejava;
import javax.swing.JFrame;
/**
*
* @author www.codejava.net
*
*/
public class SwingApp extends JFrame {
public SwingApp() {
super("Swing App");
setSize(400, 300);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
If we run the MyApp program from command line, we can write:
java MyApp console
Or:
java MyApp gui
But how to do that in Eclipse, especially when we want to test back and forth between the console and the GUI?Here are the steps:Click menu Run > Run Configurations… This brings up the Run Configurations dialog.You see there’s a default launch configuration which has same name as the project (MyApp in this case).
Update the field Name at the top to MyApp (console), and in the Arguments tab, type console in the text box Program arguments:Click Run button in this dialog, and you will see the program runs and prints:
Hello, this is a console app.
Now, we are going to create another launch configuration to run the program in GUI mode.Click menu Run > Run Configurations… And click the button New launch configuration at the top left corner (this is a little bit small so you may not notice):The New_configuration launch created, enter MyApp (GUI) for the field Name and specify main class like this:Switch to Arguments tab and enter gui in the Program arguments text box:Click Run button, and you will the program runs and shows a window:Awesome, righ?Now click the arrow of the Run button on the toolbar, you will see there are two options for running the program in two different configurations:It’s very convenient, isn’t it? Now you can switch back and forth between two modes of the program easily. Thanks Eclipse!
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments