Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 20

Building GUIs with AWT

The graphical user interface (refer to GUI henceforth) is an important part of the modern day application. Like
most programming libraries, the JDK allows you to develop GUI front ends by using the Abstract Windowing
Toolkit or more commonly know as the AWT.

Component and Container

The basic GUI building blocks in AWT are Components and Containers.

Component Class

Component is the base class of all AWT widgets (eg. Button, List, Choice, etc.). We will use the word component
to refer to AWT widgets collectively and Component to refer specifically to the class. As the base class,
Component provides the following methods which are common across all components:

public void paint(Graphics g)


Called when the Container needs to update the GUI. Control will be passed to this method for drawing.
Graphics is an abstraction of the screen. We will look at Container and Graphics shortly.

public void repaint()


Force an update of the component; call this method when you need to the component to be redrawn.

public void setBackground(Color c)


Sets the background color of a component.

public void setForeground(Color c)


Sets the foreground color of a component.

public void setEnabled(boolean b)


Enable or disable a component. A disabled component is grayed out and is not usable; eg. a disabled
Button cannot be pressed.

public void setFont(Font f)


Sets the font for this component.

public void requestFocus()


Set the mouse focus to this component.

The above is not an exhaustive list of all methods; please consult the Component API documentation.

Components of AWT Components of Swing


Label JLabel
Button JButton
TextField JtextField
TextArea JTextArea
CheckBox JCheckBox
RadioButton JRadioButton
ComboBox JComboBox
MenuBar JMenuBar
Menu Jmenu
MenuItem JMenuItem,
CheckBoxMenuItem JCheckBoxMenuItem,
RadioButtonMenuItem and JRadioButtonMenuItem

Components of Swing
JLabel
JLabel is a display area for a short text string or an image, or both. A label does not react to input events.

JButton
JButton is a lightweight button.

JTextField
JTextField is a lightweight component that allows the editing of a single line of text.

JTextArea
A JTextArea is a multi-line area that displays plain text.

Container Class

The Container class, as the name implies acts as a container for components. To built a GUI, you add
components in to Containers. Here is the catch: since Containers are themselves subsclass of Component, you
can add Containers to Containers! Using this technique, we can build very complex GUIs.

The following are important methods in Container class:

public Component add(Component c)


Adds a component to a Container.

public Component add(String name, Component c)


Adds a component to a name location in Container.

public void setLayout(LayoutManager mgr)


Sets a LayoutManager to the Container.

Containers in AWT Containers of Swing


1. Frame 1) JFrame
2. Dialog 2) JDialog
3. Panel 3) JPanel

Lets take a bird's eyeview of building a simple GUI with Components and Containers before we proceed further.

1 import java.lang.*;
2 import java.awt.*;
3 public class AFrame {
4 public AFrame() {
5 Button button = new Button("Press Me!");
6 button.setBackground(Color.red);
7 button.setForeground(Color.white);
8 Frame frame = new Frame("A Frame");
9 frame.setLayout(new FlowLayout());
10 frame.setBackground(Color.yellow);
11 frame.add(button);
12 frame.setSize(200, 100);
13 frame.setVisible(true);
14 }
15 public static void main(String[] args) {
16 AFrame aFrame = new AFrame();
17 }
18 }

The GUI produced by the previous code snippet is shown in figure


An explanation of AFrame.java is as follows:

line 2, Unlike java.lang package which is imported by default, you have to import java.awt package manually
otherwise your program will not compile.
line 5, Recall Button is a subclass of Component. We create an instance of Button.
line 6 and 7, Sets button's foreground and background color.
line 8, We create an instance of Frame which is a subclass of Container.
line 9, Set the layout or arrangement viz. how components in frame will be arranged.
line 11, Add the button to the frame for display.
line 12, Sets the frame's size for display. The width and height is 200 by 100 pixel respectively.
line 13, Finally, when all the setup is completed, we display the frame by setting its visible property to true.

Containers of Swing

JFrame
JFrame is a lightweight top-level window with a title and a border.

Sample 1: JFrameExample
Source Code:
//JframeExample.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JFrameExample extends JFrame


{
JFrameExample()
{
setTitle( "JFrame Example" );
setSize( 540, 380 );

addWindowListener( new WindowAdapter()


{
public void windowClosing( WindowEvent eWindow )
{
System.exit( 0 );
}
}
);
}

public static void main( String[] args )


{
JFrameExample oFrame = new JFrameExample();
oFrame.setVisible( true );
}
}

JDialog
JDialog is a lightweight top-level window with a title and a border that is typically used to take some
form of input from the user. A dialog can be either modeless (the default) or modal. A modal dialog is
one which blocks input to all other toplevel windows in the application, except for any windows created
with the dialog as their owner

Sample 1: JDialogExample.java
Source Code:
// JDialogExample.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class JDialogExample extends JDialog


{
JDialogExample()
{
setTitle( "JDialog Example" );
setSize( 540, 380 );

addWindowListener( new WindowAdapter()


{
public void windowClosing( WindowEvent eWindow )
{
System.exit( 0 );
}
}
);
}

public static void main( String[] args )


{
JDialogExample oDialog = new JDialogExample();
oDialog.setVisible( true );
}
}
JPanel
JPanel is a generic lightweight container.

Sample 1: JPanelExample.java

Source Code:
// JPanelExample.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;

public class JPanelExample extends JFrame


{
JPanelExample()
{
setTitle( "JPanel Example" );
setSize( 540, 380 );

getContentPane().setLayout( new BorderLayout() );

JPanel oNorthPanel = new JPanel();


oNorthPanel.setBorder( new BevelBorder( BevelBorder.LOWERED ) );
getContentPane().add( BorderLayout.NORTH, oNorthPanel );

JPanel oSouthPanel = new JPanel();


oSouthPanel.setBorder( new BevelBorder( BevelBorder.RAISED ) );
getContentPane().add( BorderLayout.SOUTH, oSouthPanel );

addWindowListener( new WindowAdapter()


{
public void windowClosing( WindowEvent eWindow )
{
System.exit( 0 );
}
}
);
}

public static void main( String[] args )


{
JPanelExample oFrame = new JPanelExample();
oFrame.setVisible( true );
}
}
LayoutManager

The layout of components within a Container is done by LayoutManager. Before you add any components to a Container you
need to set the layout or arrangement of the Container using setLayout() method. The LayoutManager controls the placement
of components according to it’s the LayoutManager's layout policy. The LayoutManager controls all aspect of a component
in the Container: its placement, size, orientation, etc.

The JDK comes with 5 LayoutManagers. We will examine only the following 3: FlowLayout, GridLayout and BorderLayout.

FlowLayout
FlowLayout arranges components in a Container like sentences in a page; from left to right and from top to
bottom. FlowLayout will try to fit as many components on a line as possible before moving them to the next. When
you resize a Container, FlowLayout will rearranges the components according to the new Container's size.

The following code adds 3 Buttons to a FlowLayoutmanaged Container.

1 import java.lang.*;
2 import java.awt.*;
3 public class FlowLayoutEx {
4 public FlowLayoutEx() {
5 Frame frame = new Frame("FlowLayout");
6 frame.setLayout(new FlowLayout());
7 frame.add(new Button("One"));
8 frame.add(new Button("Two"));
9 frame.add(new Button("Three"));
10 frame.setSize(200, 100);
11 frame.setVisible(true);
12 }
13 public static void main(String[] args) {
14 FlowLayoutEx ex = new FlowLayoutEx();
15 }
16 }

Notice that in line 6, we set the FlowLayout to be the layout of the frame. All subsequent add ( line 7 to 9) will be
under FlowLayout's control. When you run FlowLayoutEx program, you will see the frame as shown in figure.
When the frame is resized, the buttons will adjust to accommodate the new size.

Figure 5.2: Container managed by FlowLayout

GridLayout

The GridLayout devides the Container into a specified number of rows and columns, very much like a matrix.
Components in the grid are arranged from left to right and from top to bottom. The size of each cell is the size of
the largest component in the grid.

The following code snippet creates a 3 rows by 2 columns grid.


1 import java.lang.*;
2 import java.awt.*;
3 public class GridLayoutEx {
4 private String[] label = {"A", "B", "C", "D", "E", "F" };
5 public GridLayoutEx() {
6 Frame frame = new Frame("GridLayout");
7 frame.setLayout(new GridLayout(3, 2));
8 for (int i = 0; i < label.length; i++)
9 frame.add(new Button(label[i]));
10 frame.pack();
11 frame.setVisible(true);
12 }
13 public static void main(String[] args) {
14 GridLayoutEx ex = new GridLayoutEx();
15 }
16 }

Container managed by GridLayout


BorderLayout

BorderLayout divides a container into 5 region. They are “north", “south", “east", “west" and “center". When you
add a component to a BorderLayout managed container, you need to specify the region or your component will
not show up when you display the container.

The following code adds 5 buttons to the 5 region in BorderLayout.

1 import java.lang.*;
2 import java.awt.*;
3 public class BorderLayoutEx {
4 public BorderLayoutEx() {
5 Frame frame = new Frame("BorderLayout");
6 frame.setLayout(new BorderLayout());
7 frame.add(new Button("North"), BorderLayout.NORTH);
8 frame.add(new Button("South"), BorderLayout.SOUTH);
9 frame.add(new Button("East"), BorderLayout.EAST);
10 frame.add(new Button("West"), BorderLayout.WEST);
11 frame.add(new Button("Center"), BorderLayout.CENTER);
12 frame.setSize(200, 200);
13 frame.setVisible(true);
14 }
15 public static void main(String[] args) {
16 BorderLayoutEx ex = new BorderLayoutEx();
17 }
18 }

Note lines 7 to 11; we specify the region the component is to be added. The _rst parameter of add() is the
component itself, in this case a Button while the second is the position. The result of BorderLayoutEx is shown in
figure

SwingApplication

Source Code:
// SwingApplication.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SwingApplication


{
public static void main( String[] args )
{
JFrame oFrame = new JFrame( "My Frame" );
oFrame.setBackground( Color.blue );
oFrame.setSize( 540, 380 );
oFrame.setVisible( true );
oFrame.addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent eWindow )
{
System.exit( 0 );
}
}
);
}
}
Layout Management

1. FlowLayout

Source Code:
// FlowLayoutTest.java
import java.awt.*;
import javax.swing.*;

public class FlowLayoutTest extends JFrame


{
FlowLayoutTest( String sTitle )
{
super( sTitle );

// Sets the size of the frame to 540x380 (widthxheight)


oFrame.setSize( 540, 380 );

// Centers the frame


oFrame.setLocationRelativeTo( null );

getContentPane().setLayout( new FlowLayout() );


getContentPane().add( new JButton( "Button 1" ) );
getContentPane().add( new JButton( "Button 2" ) );
getContentPane().add( new JButton( "Button 3" ) );
getContentPane().add( new JButton( "Button 4" ) );
getContentPane().add( new JButton( "Button 5" ) );
}
public static void main( String[] args )
{
// Create a frame with five buttons in FlowLayout.
// The frame title is FlowLayoutTest.
FlowLayoutTest oFrame = new FlowLayoutTest( "FlowLayoutTest" );
// Displays the frame.
oFrame.setVisible( true );
}
}

2. GridLayout

Source Code:
// GridLayoutTest.java
import java.awt.*;
import javax.swing.*;

public class GridLayoutTest extends JFrame


{
GridLayoutTest( String sTitle )
{
super( sTitle );

// Sets the size of the frame to 540x380 (widthxheight)


oFrame.setSize( 540, 380 );

// Centers the frame


oFrame.setLocationRelativeTo( null );

getContentPane().setLayout( new GridLayout( 2, 3 ) );


getContentPane().add( new JButton( "Button 1" ) );
getContentPane().add( new JButton( "Button 2" ) );
getContentPane().add( new JButton( "Button 3" ) );
getContentPane().add( new JButton( "Button 4" ) );
getContentPane().add( new JButton( "Button 5" ) );
}
public static void main( String[] args )
{
// Create a frame with five buttons in GridLayout.
// The frame title is GridLayoutTest.
GridLayoutTest oFrame = new GridLayoutTest( "GridLayoutTest" );

// Displays the frame.


oFrame.setVisible( true );
}
}

3. BorderLayout

Source Code:
// BorderLayoutTest.java
import java.awt.*;
import javax.swing.*;

public class BorderLayoutTest extends JFrame


{
BorderLayoutTest( String sTitle )
{
super( sTitle );

// Sets the size of the frame to 540x380 (widthxheight)


setSize( 540, 380 );

// Centers the frame


setLocationRelativeTo( null );

getContentPane().setLayout( new BorderLayout() );


getContentPane().add( BorderLayout.NORTH, new JButton( "Button 1" ) );
getContentPane().add( BorderLayout.SOUTH, new JButton( "Button 2" ) );
getContentPane().add( BorderLayout.EAST, new JButton( "Button 3" ) );
getContentPane().add( BorderLayout.WEST, new JButton( "Button 4" ) );
getContentPane().add( BorderLayout.CENTER, new JButton( "Button 5" ) );
}
public static void main( String[] args )
{
// Create a frame with five buttons in BorderLayout.
// The frame title is BorderLayout.
BorderLayoutTest oFrame = new BorderLayoutTest( "BorderLayoutTest" );

// Displays the frame.


oFrame.setVisible( true );
}
}

Building Complex GUI in Swing

Sample 1: ComponentsSample

Source Code:
// ComponentsSample1
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ComponentsExample1 extends JDialog


{
ComponentsExample1()
{
setTitle( "Components Example(1)" );
setSize( 540, 380 );

getContentPane().setLayout( new BorderLayout() );

JPanel oNorthPanel = new JPanel();


oNorthPanel.setLayout( new FlowLayout() );

JLabel oLabel = new JLabel( "I am a JLabel." );


oNorthPanel.add( oLabel );

JTextField oTextField = new JTextField( "I am a JTextField", 25 );


oNorthPanel.add( oTextField );

getContentPane().add( BorderLayout.NORTH, oNorthPanel );

JTextArea oTextArea = new JTextArea( "I am a JTextArea", 10, 10 );


getContentPane().add( BorderLayout.CENTER, oTextArea );

JButton oButton = new JButton( "I am a JButton." );


getContentPane().add( BorderLayout.SOUTH, oButton );

addWindowListener( new WindowAdapter()


{
public void windowClosing( WindowEvent eWindow )
{
System.exit( 0 );
}
}
);
}

public static void main( String[] args )


{
ComponentsExample1 oDialog = new ComponentsExample1();
oDialog.setVisible( true );
}
}

Sample 2: ComponentsSample2
Source Code:
// ComponentsSample2.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ComponentsExample2 extends JFrame


{
ComponentsExample2()
{
setTitle( "Components Example(2)" );
setSize( 540, 380 );

getContentPane().setLayout( new BorderLayout() );

JPanel oCenterPanel = new JPanel();


oCenterPanel.setLayout( new FlowLayout() );

JCheckBox oCheckBox = new JCheckBox( "I am a JCheckBox", true );


oCenterPanel.add( oCheckBox );

JRadioButton oRadioButton1 = new JRadioButton( "I am a JRadioButton." );


JRadioButton oRadioButton2 = new JRadioButton( "I am a JRadioButton too." );

ButtonGroup oButtonGroup = new ButtonGroup();


oButtonGroup.add( oRadioButton1 );
oButtonGroup.add( oRadioButton2 );

oCenterPanel.add( oRadioButton1 );
oCenterPanel.add( oRadioButton2 );

JComboBox oComboBox = new JComboBox();


oComboBox.addItem( "I" );
oComboBox.addItem( "am" );
oComboBox.addItem( "a" );
oComboBox.addItem( "ComboBox" );
oComboBox.setSelectedIndex( 3 );
oComboBox.setEditable( false );

oCenterPanel.add( oComboBox );

getContentPane().add( BorderLayout.SOUTH, oCenterPanel );

JMenuBar oMenuBar = new JMenuBar();

JMenu oMenu = new JMenu( "Menu" );


oMenu.setMnemonic( 'M' );
oMenuBar.add( oMenu );

JMenuItem oMenuItem = new JMenuItem( "Menu Item" );


oMenu.add( oMenuItem );

oMenu.addSeparator();

JCheckBoxMenuItem oCheckBoxMenuItem = new JCheckBoxMenuItem( "CheckBox Menu


Item" );
oCheckBoxMenuItem.setMnemonic( 'C' );
oMenu.add( oCheckBoxMenuItem );

JRadioButtonMenuItem oRadioButtonMenuItem = new JRadioButtonMenuItem( "RadioButton


Menu Item" );
oMenu.add( oRadioButtonMenuItem );

oMenu.addSeparator();

JMenu oSubMenu = new JMenu( "Sub-Menu" );


oMenu.add( oSubMenu );

JMenuItem oSubMenuItem = new JMenuItem( "Sub-Menu Item" );


oSubMenu.add( oSubMenuItem );
oSubMenuItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_S, 2 ) );

setJMenuBar( oMenuBar );

addWindowListener( new WindowAdapter()


{
public void windowClosing( WindowEvent eWindow )
{
System.exit( 0 );
}
}
);
}

public static void main( String[] args )


{
ComponentsExample2 oFrame = new ComponentsExample2();
oFrame.setVisible( true );
}
}
Event Handling

Event-Delegation Model
In Java, events are objects. The java.awt.event. package defines a rich hierarchy of event types. Through this
package, instances of the various event classes are constructed when users are GUI components. It is up to the
programmer to decide how to handle the generated event. For example, when a user clicks a button, the system
constructs an instance of class ActionEvent, in which it stores details about the event (when, where, and so on).
At this point, the programmer has three options:

 Ignore the event.


 Have the event handled by the component (in this case, a button) where the event originated.
 Delegate event handling to some other object, possibly yourself, or objects called listeners.

Sample 1: Handling the Event in the Originating Component


// SelfButton.java
import java.awt.*;
import java.awt.event.*;

public class SelfButton extends Button


{
public SelfButton( String sLabel )
{
super( sLabel );
enableEvents( AWTEvent.ACTION_EVENT_MASK );
}

public void processActionEvent( ActionEvent eAction )


{
super.processActioNEvent( eAction );
System.out.println( "Action!" );
}
}

Sample 2: Delegating the event.


The process of assigning an object to handle a component’s events is called “delegation”. The event-handling
objects are called “listeners”.

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

public class ButtonDelegateTest extends JDialog


{
ButtonDelegateTest()
{
setTitle( "Button Delegate Test" );
setSize( 540, 380 );

getContentPane().setLayout( new FlowLayout() );

JButton oButton = new JButton( "PRESS ME PLEASE" );


oButton.addActionListener( new TestListener() );

getContentPane().add( oButton );
addWindowListener( new WindowAdapter()
{
public void windowClosing( WindowEvent eWindow )
{
System.exit( 0 );
}
}
);
}

class TestListener implements ActionListener


{
public void actionPerformed( ActionEvent eAction )
{
System.out.println( "You just pressed me!!!" );
}
}

public static void main( String[] args )


{
ButtonDelegateTest oDialog = new ButtonDelegateTest();
oDialog.setVisible( true );
}
}

You might also like