- First, we must import the AWT packages -
import java.awt.*;
import java.awt.event.*;
- Next we create a container to hold the components that we
need. For applications we create a subclass of frame so that we
can override the methods to create the GUI -
class SimpleGui extends Frame
{
// constructor
public SimpleGui()
{
}
}
- Now we can create and configure the visual components needed. To display
a single line of read-only text we use a Label object -
// component to be added to the Frame
Label msg;
// constructor
public SimpleGui()
{
// initialise label
// Label constructor takes text to be displayed as first argument
// Optional second argument gives text justification
msg = new Label("Hello World", Label.CENTER);
}
- Now add the Label component to the Frame container -
// constructor
public SimpleGui()
{
// initialise label
msg = new Label("Hello World", Label.CENTER);
// add label to Simple GUI
add(msg);
}
- Finally, add code needed to enable the user to close the window
(this is an example of event-handling in Java) -
// constructor
public SimpleGui()
{
// initialise Label
msg = new Label("Hello World", Label.CENTER);
// add Label to Simple GUI
add(msg);
// this code enables you to close the window
addWindowListener(new WindowAdapter ()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
- This gives the complete code for the class SimpleGui. Now we
can write a test program to display it -
class HelloWorld {
public static void main (String [] args)
{
SimpleGui testGui = new SimpleGui();
// set size of GUI
testGui.setSize(200,100);
// and make it visible
testGui.setVisible(true);
}
}
- You must set the size of the GUI and make it
visible.
The code for