Applications
Remember the HelloWorldApp.java
// Sample HelloWorld application
class HelloWorldApp {
public static void main(String args[]) {
System.out.println("Hello World!"); } }
You might have noticed the main().
In the above, Java takes whatever is passed in as input and gives it to the main method as an array of Strings. These strings are
the command-line arguments (as in C). You have access to any arguments that follow the
application call. The user does not make the arguments Strings (i.e., you do not use "" for integers, etc.) you just pass whatever it is you want.
E.g.
class HelloWorld2 {
public static void main(String args[]) {
int i, count;
count=args.length;
if (count > 0) {
for (i=0; i < count; i++) {
System.out.println(args[i]); }
}
else {
System.out.println("no args");
}
}
}
(indexes in arrays start at 0)
java myprog arg1 arg2 arg3
(note: no extension of .class or .java)
note: in applets, you use the HTML attributes to pass arguments ... remember
<param name=image value="duke">
then in code use: getParameter("image")
main
A program needs to be started. In Java, the starting "class" needs a main() method.
When you run your Java application (javac to compile, java to run) the first thing that gets called is
main().
The signature for main() must be:
public static void main(String arg[]) { }
The body of the main() method contains any code you need to get your application started -
creating instances, etc.
When Java executes the main() method, keep in mind that main() is a class method - the class that
holds it is not automatically instantiated when your program runs. If you want to treat that class as
an object, you have to instantiate it in the main() method yourself.
also
An important thing to note about the arguments you pass to a java program is that those arguments
will be stored in an array of strings. This means that any arguments you pass to your program will
be converted to strings so they can be stored in the argument array. To treat them as non-strings,
you'll need to convert them to whatever type you want them to be.
There must be exactly one main() in an application. Where is is? Could be in any class you put it.
A suggestion: (to be ontologically honest in OO)
Main() should really only be something to get the program going. For instance, maybe it opens a
window or frame to instantiate a user-interface. In OO, one should always think of where methods
should really reside...who is in charge of what. Since starting a system going is not really any
certain classes responsibility, perhaps (for OO purposes and for your own book-keeping (where
IS that stupid main() ) you might consider making a class called
Main with one method main()
public class Main{
public static void main(String arg[]) {
...
} } //also provides easy transfer to applets (see web)
Then whenever you want to start a program, you call:
java Main
Frames
See
java.awt.Frame or JFrame
In Java, a Frame is the base window used to create GUIs. In a typical browser, the Frame class is
a parent class for the displayed GUI. (Frame is the parent of AppletViewer)
Frame extends Window (a blank window with no borders and no menubar)
Window is typically for pop-up kind of idea
Frame gives window a border, a layout, and a title.
The AppletViewer extends Frame to include a menubar and a drawing panel.
An example of the use of Frames:
Memo Application
Java is a full object-oriented language (not just for applets)
We will now look at how to do the same things we did with graphics for applets on Frames for
applications.
A small application can be seen in the Memo Frame.
The application will pop up a frame and display a message on the frame (the message can come
from the command line, or it can be a default message (see Constructor)). If the user clicks in the
window, the application will exit.
import java.awt.event.*;
import java.awt.*;
/* Memo.java
* A simple stand-alone graphical application - in 1.1 */
class Memo extends Frame {
public String message;
public Memo(String s) {
super("Memo Frame");
// set our title
message = s;
setSize (300, 300);
}
public Memo() {
this("This is a Memo");
// constructor is done in previous method
}
This class has two constructors Memo() and
Memo(String s) - depending on if a variable is passed
public void paint(Graphics g) {
g.drawString(message, 50, 50);
g.drawString("Click anywhere to Exit", 50, 70);
}
public void start ( ) {
show();
this.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e){
setVisible(false);
//hide() the window
dispose();
// free up system resources
System.exit(0); }});
// Quit the app.
}
// Use MouseAdaptor so don't have to do all of the
// MouseListener Interface
public static void main(String args[]) {
Memo m;
if (args.length > 0)
m = new Memo(args[0]);
else m = new Memo();
m.start( );
}
Memo.java
You will also find pack() useful when you have multiple components:
pack(). Method in class java.awt.Window
Causes subcomponents of this window to be laid out
at their preferred size.
setVisible(boolean) - was hide() and show() makes the frame (and any attached components)
visible
dispose() - frees up system resources occupied by frame
only use when completely done with frame
Menus
Menu optionsMenu;
optionsMenu = new Menu ("Options");
Add items
optionsMenu.add(my = new MenuItem("mychoice"))
optionsMenu.add(your = new MenuItem("yourchoice"))
Menu Events
When you select a menu item, the event generated is an ActionEvent. You need an ActionListener
interface. Note the use of inner classes to implement the interface:
my.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println ("this is mine") }});
// or do cool things
your.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println ("this is yours") }});
// or do cool things
You can also add Checkbox menu items, division lines and submenus.
Menu m,n,optionsMenu;
MenuItem q,r,t,u;
CheckboxMenuItem s;
MenuBar mb;
public MenuTest() {
super("MenuTest");
// set the title of the frame
m = new Menu ("Examples");
optionsMenu = new Menu ("Options");
m.add(q= new MenuItem("Basic"));
m.add(r= new MenuItem("Simple"));
// add a separator
m.add(new MenuItem("-"));
// add a Checkbox item
m.add(s= new CheckboxMenuItem("Check"));
// add a submenu
n = new Menu("More Examples");
n.add(t= new MenuItem("Sub Basic"));
n.add(u= new MenuItem("Sub Simple"));
m.add(n);
q.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println ("this is :" +
((MenuItem)e.getSource()).getLabel()) ;}});
// or do cool things
r.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println ("this is:" +
((MenuItem)e.getSource()).getLabel()) ; }});
// or do cool things
s.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e){
String label = ((CheckboxMenuItem)e.getSource()).getLabel();
System.out.println ("The new checkbox is " + label);
}});
t.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println ("this is :" +
((MenuItem)e.getSource()).getLabel()) ; }});
// or do cool things
u.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println ("this is:" +
((MenuItem)e.getSource()).getLabel()) ; }});
// or do cool things
Now, place it in the application's menu bar:
mb = new MenuBar();
mb.add(m);
mb.add(optionsMenu);
Set menu bar for the frame
All together now (1.1) and as seen in real life
import java.awt.*;
import java.awt.event.*;
public class MenuTest extends Frame {
Menu m,n,optionsMenu;
MenuItem q,r,t,u;
CheckboxMenuItem s;
MenuBar mb;
public MenuTest() {
super("MenuTest");
// set the title of the frame
m = new Menu ("Examples");
optionsMenu = new Menu ("Options");
m.add(q= new MenuItem("Basic"));
m.add(r= new MenuItem("Simple"));
// add a separator
m.add(new MenuItem("-"));
// add a Checkbox item
m.add(s= new CheckboxMenuItem("Check"));
// add a submenu
n = new Menu("More Examples");
n.add(t= new MenuItem("Sub Basic"));
n.add(u= new MenuItem("Sub Simple"));
m.add(n);
q.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println ("this is :" +
((MenuItem)e.getSource()).getLabel()) ; }});
// or do cool things
r.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println ("this is:" +
((MenuItem)e.getSource()).getLabel()) ; }});
// or do cool things
s.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e){
boolean label = ((CheckboxMenuItem)e.getSource()).getState();
System.out.println ("The new checkbox state is " + label);
}});
t.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println ("this is :" +
((MenuItem)e.getSource()).getLabel()) ; }});
// or do cool things
u.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
System.out.println ("this is:" +
((MenuItem)e.getSource()).getLabel()) ; }});
// or do cool things
mb = new MenuBar();
mb.add(m);
mb.add(optionsMenu);
setMenuBar(mb);
}
public void start() {
setSize(300, 300);
show();
}
public static void main(String args[]) {
MenuTest m = new MenuTest();
m.start();
}
}
***Note PopupMenu and MenuShotcut in ScribbleFrame (Nutshell2)
http://www.ecst.csuchico.edu/~amk/foo/javanut2/index.html (example 8-1)
To create a popup menu, create a PopUpMenu, and add MenuItem objects to it. Do as you
would with a regular menu pane. However, instead of adding a popupmenu to the menubar, you
add it to the component over which it pops up. This is done with the add() method of the target
component.
See also MenuShortcut
MenuShortcut s = new MenuShortcut(KeyEvent,VK_C);
is a shortcut invoked as a Ctrl-C (platform independent ...cool). VK_ are Virtual Key constants
defined in the KeyEvent class
Here is another example of an application (a decimal converter): download and run
import java.awt.*;
import java.awt.event.*;
public class d2x extends Frame implements ActionListener{
int decimalValue = 0;
String baseXValue = new String("0");
TextField dDisplay, xDisplay;
public d2x() {
super("Decimal Converter"); // set the title of the frame
MenuBar mb = new MenuBar();
Button d2Binary = new Button("Binary");
Button d2Octal = new Button("Octal");
Button d2Hex = new Button("Hex");
Button d2Base36 = new Button("Base36");
Panel p1 = new Panel();
Panel p2 = new Panel();
Panel p3 = new Panel();
// add a simple menu
Menu m = new Menu("Application");
MenuItem exit = new MenuItem("Exit");
m.add(exit);
//add menu to menubar
mb.add(m);
setMenuBar(mb); // install this menu bar in the frame
// Add buttons to their own panel
p3.setLayout(new FlowLayout());
p3.add(d2Binary);
p3.add(d2Octal);
p3.add(d2Hex);
p3.add(d2Base36);
// Add text fields
Label dLabel = new Label("Enter Decimal: ");
Label xLabel = new Label("Converted Value:");
dDisplay = new TextField(Integer.toString(decimalValue),7);
xDisplay = new TextField(baseXValue,32);
xDisplay.setEditable(false);
p1.setLayout(new FlowLayout(FlowLayout.LEFT));
p2.setLayout(new FlowLayout(FlowLayout.LEFT));
p1.add(dLabel);
p1.add(dDisplay);
p2.add(xLabel);
p2.add(xDisplay);
// Add the panels
add("North",p1);
add("Center",p2);
add("South",p3);
// Add listeners
d2Binary.addActionListener(this);
d2Octal.addActionListener(this);
d2Hex.addActionListener(this);
d2Base36.addActionListener(this);
exit.addActionListener(this);
}
public void start() {
setSize(500, 250);
setVisible(true);
}
public void updateXDisplay() {
xDisplay.setText(baseXValue);
}
public void actionPerformed(ActionEvent evt) {
// Get the "action command" of the event, and dispatch based on that.
Object source = evt.getSource();
if (source instanceof MenuItem) {
System.out.println("got here");
System.out.println(((MenuItem)source).getLabel());
if ("Exit".equals(((MenuItem)source).getLabel())) {
System.out.println("Exiting...");
setVisible(false);
dispose();
System.exit(0);
}
}
else if (source instanceof Button) {
String which = ((Button)source).getLabel();
if (which.equals("Binary")) {
decimalValue = Integer.parseInt(dDisplay.getText());
baseXValue = Integer.toString(decimalValue,2);
}
if (which.equals("Octal")) {
decimalValue = Integer.parseInt(dDisplay.getText());
baseXValue = Integer.toString(decimalValue,8);
}
if (which.equals("Hex")) {
decimalValue = Integer.parseInt(dDisplay.getText());
baseXValue = Integer.toString(decimalValue,16);
}
if (which.equals("Base36")) {
decimalValue = Integer.parseInt(dDisplay.getText());
baseXValue = Integer.toString(decimalValue,36);
}
updateXDisplay();
}
}
public static void main(String args[]) {
d2x m = new d2x();
m.start();
}
}
Notice the main() - instantiates and starts