Previous
Index

Next

1.5) A Graphical HelloWorld

Fire up your favourite editor and create the following code in a file called HelloAp.java Remember as ever, Java is utterly case sensitive.

/* HelloAp */
// A Single line comment
import javax.swing.*;
import java.awt.*;

public class HelloAp extends JFrame{
JButton button;
JTextField jtf;
    public static void main(String argv[]){
        HelloAp helloap = new HelloAp();
        helloap.go();
    }
    public void go(){
        button = new JButton("Hello");
	  jtf = new JTextField();
        setLayout(new FlowLayout());
        add(button);
        add(jtf);
        setSize(100,100);       
        setVisible(true);
    }
}

Compile this code by typing

javac HelloAp.java

You are now ready to test your first graphical Java program. From the command prompt type

java HelloAp

This is a screen shot from this code running under Linux, the result under Windows should be similar.



Line by line analysis of the graphical HelloWorld

/* HelloAp */
// A Single line comment

These two lines are comments, text put into the program to explain the code not to actually change how the program works. The first line using the /* version of comments means the comment will continue until it is closed by a matching */ set of characters. The second version // is a comment that stops at the end of the line.

import javax.swing.*;

These lines tell the compiler that you will be using these classes. Although this can seem a bit like the use of the

#include

pre-processor directive in C/C++, it is actually more like the DOS path statement. If that doesn't mean anything to you don't worry right now. The import directive statement is used to integrate Java classes already in existence. In this case

javax.swing.*;

is a reference to the Swing classes. This contains the basic Graphic components such as buttons, frames, labels, etc. etc.

public class HelloAp extends JFrame{

This line is similar to the line in the stand alone code that declared the HelloWorld class. The important difference is the part that states

extends JFrame

The keyword extends means that this class will extend an already existing class. This actually means

extends javax.swing.JFrame

But because of the import statement at the start of the program you do not need to specify the javax.swing part of the JFrame class name. This is part of the Java inheritance mechanism. By extending the Frame class this new class will obtain the functionality of the Frame class such as the ability to add components and repaint itself.

JButton button;

This code announces that there will be an instance of Jbutton available within the class. It would be possible to make this declaration within the method that uses it, but by making it a class field allows the button to be used in other methods (this becomes important later on when we cover event handling).

        HelloAp helloap = new HelloAp();

The main method has a line to create a new instance of the HelloAp class, this is because the main method is static and we need a new instance from which to call instance methods. Once an instance has been created the go method is called to start the program running. The choice of the method name go is entirely arbitrary.

The go method starts by creating an instance of the JButton class, which as you can guess from its name acts like a button, i.e. it can be clicked and can have a label indicating what it is to be used for. In this example we don't actually program the button to do anything.

button = new JButton("Hello");

This line is to create a new instance of the Button class. Note that the program knows about the Button class because of the line

import javax.swing.*;

at the start of the code. The asterisk (*) means make all of the classes from the Swing classes available. For the purposes of this program it would also be acceptable to have the import declarations as

import javax.swing.JFrame;
import javax.swing.JButton;

The JButton has been sent the String "Hello World" as part of its constructor (initialisation code).

The next line reads

add(button);

The important bit of this line is the call to the add method. This adds the button to the current class instance. The last two lines set the size of the frame and then ask it to display itself. Note that the final closing brace is not terminated with a semi colon.

This graphical HelloAp is the basic structure of most Java graphical applications. Most applications involve creating a Frame, adding components such as menus, buttons, labels and text entry fields and then processing the events that happen when the user uses the mouse or enters data.


Exercise: StopSign

Create a class called StopSign that extends JFrame. The class should create an instance of itself and call a go method that creates a button containing the string Stop. Create code that sets the background color of the word Stop to red. A tip: You need to include java.awt.color, and you can set the color red with Color.RED. Use the setBackground method.

Adding multiple components

You might think that you can add additional components simply by creating instances and adding them to the application. However by default any new components will just be added on top of any existing ones. To avoid this problem a program needs to change the “layout manager”. I will cover layout managers in detail elsewhere, but for the moment I will just cover enough to allow you to add multiple components. The following example just adds a text field.

/**
Marcus Green 2007
Adding Multiple components
**/

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class MulComp extends JFrame {
    public static void main(String argv[]){
        MulComp mc = new MulComp();
        mc.go();
    }
    public void go(){
        JButton button = new JButton("Hello");
        JTextField tf = new JtextField("Hello");
        /**This is where the magic happens */
        setLayout(new FlowLayout());
        add(button);
        add(tf);
        setSize(100,100);       
        setVisible(true);
    }
}





Exercise: Login screen

Create a class called Login that extends JFrame. Set the layout to allow multiple components. Add a JTextField and a JPasswordField. Use the setColumns method of the components to set the width of the elements. Add instances of the JLabel class to label each field with the text “Name” and “Password”. Compile and run the application to see what it does. Try resizing the pane to see what happens to the placing of the components.



Previous
Index

Next