Sunncity.com - Developer & I.T. Zone

 
Sunncity Web

Technology Menu

Developer Center
Delphi Online Tutorial
JAVA Online Tutorial
The Code Project
XML Code Library
FREE Download
Our Free Components
Our Free Software
Free Components
Delphi & Kylix Training
SMTC Training Course
About Delphi EXAM

Search Component


Search Software(s)


by oneNetwork

 

Java Online Tutorial - AWT VS SWING
The Java Awt or Graphic User Interfaces

Java provides the awt for all your GUI building needs. You have frames, panels, labels, buttons, checkboxes, radiobuttons, choices, lists, scrollpanes and more. You have at least five different layout schemes with which to lay out your applet or application. You have a whole range of listeners which can listen for different types of events like the ActionListener, KeyListener, WindowListener, ItemListener and more. Before I re-write the entire api for you, I would like to stop. Suffice to say that whatever GUI you are interested in - the Awt can build it for you.

And as if that wasn't enough, the makers of Java had to go and make Swing too. The Awt and Swing are very much similar. To port your java source code from the awt to swing, all you have to do is import javax.swing.* extend JApplet instead of Applet and place a J before each of your components. E.g. JPanel for Panel, JFrame for Frame etc. In addition, Swing offers some very advanced components like JTree, JEditorPane, JTextPane and JInternalFrame. A complete rendition of all the components will be impossible here. Swing will be covered in a separate chapter. Here we will try to explain only a few of the common components of the awt and how to use them. This chapter will be divided into three sections.


Components

To use a component, e.g a Button - you have to perform five steps.

  • Make a button.
  • Button button1 = new Button("One");
  • Add it to a container.
  • add(button1);
  • Add a listener to it.
    addActionListener(this);
  • Provide a method body to define the behaviour of the button in response to a button click.
  • public void actionPerformed(ActionEvent e) { 
                                }
  • In the class declaration add "implements ActionListener".

That's it. See a full example below. The steps for adding other components are the same. Follow the logic and you will see that it is really quite simple.


import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Buttons extends Applet {
 Label label = new Label("Default Label");
 Button button1 = new Button("One");
 Button button2 = new Button("Two");
 Button button3 = new Button("Three");
 Panel panel1 = new Panel();
 Panel panel2 = new Panel();

	public void init() {
	setLayout(new BorderLayout());
	panel1.add(label);
	button1.addActionListener(new ButtonHandler());
	button2.addActionListener(new ButtonHandler());
	button3.addActionListener(new ButtonHandler());
	panel2.add(button1);
	panel2.add(button2);
	panel2.add(button3);
	add("North",panel1);
	add("Center",panel2);
 	}

 class ButtonHandler implements ActionListener {
	  public void actionPerformed(ActionEvent e){
	   String s = e.getActionCommand();
	   label.setText(s);
  }
 }
}

A running version sample of the applet is available here .

Back to TOP


Layouts

In the Awt there are five different layouts. You set the layout by using setLayout(new GridLayout(0,1)) as an example. The first argument is the number of rows and the second is the number of columns. If you're in a Panel there's no need to explicitly set the layout to FlowLayout because Panel by default uses a FlowLayout.

  • The FlowLayout
    This the default for Panel and Applet. You add a component by add(component);Components are added left to right first and then top to bottom one after the other in the same order in which they were added.
  • The BorderLayout
    Add a component using add(component, BorderLayout.CENTER) where the second argument can be one of NORTH, SOUTH, EAST, WEST and CENTER. The center component occupies most of the space with the others being mere strips on the sides.
    This is the default for Frame and Dialog.
  • The CardLayout
    Add as many component as you like using add(component, String key);The second argument can be any String. Only one component will be visible at a time. Set the component which is visible by calling show(component ,String.valueOf(key));
  • The GridLayout
    Arranges the display in as a series of grids of equal size.
  • The GridBagLayout
    This allows you more flexibility in terms of the positioning. You will seldom be needing GridBag, however.

In addition to the above Swing provides a few more layout schemes among which BoxLayout and OverlayLayout are useful. Lastly, I would like to mention the null layout, which isn't actually a layout scheme but you can use it when you want to control the exact positioning of the components which you set by a call to setBounds(x, y, width, height);where x, y stand for the coordinates of the upper left corner where you want to place the component.

Check out the following applet for an example of the most common layout schemes.


import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class Layouts extends Applet {
Panel[] panels;
Panel currentPanel;
static int border=0;
static int card=1;
static int flow=2;
static int grid=3;
static int gridBag=4;
String[] layouts = {"Border","Card","Flow","Grid","GridBag"};
String[] cards = {"First","Last","Next","Previous"};
Button[] layoutButtons = new Button[layouts.length];
Button[] navigateButtons = new Button[cards.length];
Panel layoutButtonPanel = new Panel();
Panel navigateButtonPanel = new Panel();
	 
public void init(){
setLayout(new BorderLayout());
setupButtons();
add("North",layoutButtonPanel);
setupDisplayPanels();
}

void setupButtons() {
for(int i=0;i;<layouts.length;++i) {
layoutButtons[i] = new Button(layouts[i]);
layoutButtons[i].addActionListener(new ButtonHandler());
layoutButtonPanel.add(layoutButtons[i]);
}
for(int i=0;i;<cards.length;++i) {
navigateButtons[i] = new Button(cards[i]);
navigateButtons[i].addActionListener(new ButtonHandler());
navigateButtonPanel.add(navigateButtons[i]);
}
}
	
void setupDisplayPanels() {
panels = new Panel[5];
for(int i=0;i;<5;++i) panels[i]=new Panel();
panels[border].setLayout(new BorderLayout());
panels[card].setLayout(new CardLayout());
panels[flow].setLayout(new FlowLayout());
panels[grid].setLayout(new GridLayout(2,3));
GridBagLayout gridBagLayout = new GridBagLayout();
panels[gridBag].setLayout(gridBagLayout);
panels[border].add("North",new Button("North"));
panels[border].add("South",new Button("South"));
panels[border].add("East",new Button("East"));
panels[border].add("West",new Button("West"));
panels[border].add("Center",new Button("Center"));
String cardButtons[] = {"First","Second","Third","Fourth","Last"};
String flowButtons[] = {"One","Two","Three","Four","Five"};
String gridButtons[] = {"(0,0)","(1,0)","(2,0)","(0,1)","(1,1)","(2,1)"};
for(int i=0;i;<cardButtons.length;++i)
panels[card].add("next card",new Button(cardButtons[i]));
for(int i=0;i;<flowButtons.length;++i)
panels[flow].add(new Button(flowButtons[i]));
for(int i=0;i;<gridButtons.length;++i)
panels[grid].add(new Button(gridButtons[i]));
Button gridBagButtons[] = new Button[9];
for(int i=0;i;<9;++i) gridBagButtons[i] = new Button("Button"+i);
int gridx[] = {0,1,2,0,2,0,1,1,0};
int gridy[] = {0,0,0,1,1,2,2,3,4};
int gridwidth[] = {1,1,1,2,1,1,1,2,3};
int gridheight[] = {1,1,1,1,2,2,1,1,1};
GridBagConstraints gridBagConstraints[] = new GridBagConstraints[9];
for(int i=0;i;<9;++i) {
gridBagConstraints[i] = new GridBagConstraints();
gridBagConstraints[i].fill=GridBagConstraints.BOTH;
gridBagConstraints[i].gridx=gridx[i];
gridBagConstraints[i].gridy=gridy[i];
gridBagConstraints[i].gridwidth=gridwidth[i];
gridBagConstraints[i].gridheight=gridheight[i];
gridBagLayout.setConstraints(gridBagButtons[i],gridBagConstraints[i]);
panels[gridBag].add(gridBagButtons[i]);
}
add("Center",panels[border]);
currentPanel=panels[border];
}

void switchPanels(Panel newPanel,boolean setNavigateButtons) {
remove(currentPanel);
currentPanel=newPanel;
add("Center",currentPanel);
remove(navigateButtonPanel);
if(setNavigateButtons) add("South",navigateButtonPanel);
validate();
}

class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent ev){
String s=ev.getActionCommand();
if(s.equals("Border")) switchPanels(panels[border],false);
else if(s.equals("Card")) switchPanels(panels[card],true);
else if(s.equals("Flow")) switchPanels(panels[flow],false);
else if(s.equals("Grid")) switchPanels(panels[grid],false);
else if(s.equals("GridBag")) switchPanels(panels[gridBag],false);
else if(s.equals("First")){
CardLayout currentLayout=(CardLayout)currentPanel.getLayout();
currentLayout.first(currentPanel);
}else if(s.equals("Last")){
CardLayout currentLayout=(CardLayout)currentPanel.getLayout();
currentLayout.last(currentPanel);
}else if(s.equals("Next")){
CardLayout currentLayout=(CardLayout)currentPanel.getLayout();
currentLayout.next(currentPanel);
}else if(s.equals("Previous")){
CardLayout currentLayout=(CardLayout)currentPanel.getLayout();
currentLayout.previous(currentPanel);
}
  }
 }
}

A running sample version of the above applet is here.

Back to TOP


Handling Events

With the exception of jdk1.02, all later versions of the jdk handle events based on an event delegation model, as opposed to the older event inheritance model. Consult the api to find out what type of event your component typically handles. For example, A textfield generates an ActionEvent when the enter key is pressed while the textfield had focus. It also generates KeyEvents. Checkboxes and RadioButtons generate ItemEvents. Clicking of the mouse and dragging it generates MouseEvents and MouseMotionEvents respectively. Enough, see the api for the rest, now we shall move onto some examples.

 

Handling Events in Radio Buttons

Radio buttons are Checkboxes which have been associated with a CheckboxGroup. You can select only one radio button at a time. As opposed to a checkbox which has not been associated with a chekboxgroup and can select more than one at a time.

The newer releases of the jdk creates radio buttons with an explicit constructor and instead of adding them to a checkboxgroup, you add them to a ButtonGroup. And Checkbox has changed to CheckBox. The method for detecting the state is is.Selected() instead of getState(). But the jdk is backward compatible, meaning that the older api methods still work with the newer api. But not the other way around.


import java.awt.*;
import java.awt.event.*;

public class MyRadioButton extends Frame implements ItemListener {
private TextField t;
private Font plainFont, boldFont, italicFont, boldItalicFont;
private CheckboxGroup fontStyle;
private Checkbox plain, bold, italic, boldItalic;

public MyRadioButton(String title) {
t=new TextField("Watch the font style change", 40);
add(t);
	
fontStyle = new CheckboxGroup();
	
plain = new Checkbox("Plain", fontStyle, true);
plain.addItemListener(this);
add(plain);
bold = new Checkbox("Bold", fontStyle, false);
bold.addItemListener(this);
add(bold);
italic = new Checkbox("Italic", fontStyle, false);
italic.addItemListener(this);
add(italic);
boldItalic = new Checkbox("Bold/Italic", fontStyle,  false);
boldItalic.addItemListener(this);
add(boldItalic);

plainFont = new Font("Serif", Font.PLAIN, 14);
boldFont=new Font("Serif", Font.BOLD, 14);
italicFont=new Font("Serif", Font.ITALIC, 14);
boldItalicFont = new Font("Serif", Font.BOLD + Font.ITALIC, 14);

setTitle(title);
setLayout(new FlowLayout());
setSize(350, 150);
show();
	
}

public void itemStateChanged(ItemEvent e) {
if (e.getSource() == plain)
t.setFont(plainFont);
else if (e.getSource() == bold)
t.setFont(boldFont);
else if (e.getSource() == italic)
t.setFont(italicFont);
else if (e.getSource() == boldItalic)
t.setFont(boldItalicFont);

}

static class WL extends WindowAdapter {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}

public static void main(String [] args) {
MyRadioButton mrframe = new MyRadioButton("MyRadioButton");
mrframe.addWindowListener(new WL());
}
}

Using a TextField

This is also an application. You can easily convert it to an applet. This is left as an exercise to the reader. TextFields can generate KeyEvents, TextEvents, FocusEvent and ActionEvents and more. However a TextArea cannot generate an ActionEvent, only KeyEvent, FocusEvent and TextEvent, among others.


import java.awt.*;
import java.awt.event.*;

public class TextTest extends Frame implements TextListener {
	
TextField ta1, ta2;
	
public TextTest(String title) {
ta1=new TextField(10);
ta2=new TextField(10);
add(ta1);
add(ta2);
ta1.addTextListener(this);
		
setTitle(title);
setLayout(new FlowLayout());
setSize(300, 150);
show();
}
	
public void textValueChanged(TextEvent e) {
ta2.setText(ta1.getText());
}

public static void main(String args[]) {
TextTest tt= new TextTest("TextTest");
tt.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
} );
}

}

Be sure to try out the examples. A zip file of all the examples is available for download..

Back to TOP

 

Now on to the next chapter Advanced GUI - Swing


All questions and comments can be addressed to the author.
All material appearing within this website is copyright protected and may not be reproduced elsewhere without the express written permission of the author (Sanjeev Dasgupta)

 


Support this site BUY from Sunncity Gift Store