Wednesday, July 31, 2013

GridLayout

GridLayout is another layout manager. It displays components in a grid or table. A cell of the grid or table is for one component. You have three ways to create a grid layout manager by using the following constructors:

-GridLayout()
creates a grid layout that has only one column.
-GridLayout(int rows, int columns)
creates a grid layout with specified number of rows and columns.
-GridLayout(int rows,int columns,int hor,int ver)
creates a grid layout with specified number of rows and columns, and spaces between components.

In the example code below, a grid layout with five rows and two columns is created. Each cell of the grid contains a button object.

import java.awt.Button;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
InterfaceShow(String title){
setTitle(title);
setLayout(new GridLayout(5,2));
setSize(new Dimension(500,300));
setBackground(Color.BLACK);
setVisible(true);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
for(int i=0;i<10;i++){

add(new Button(i+""));
}

validate();
}
}
public class GridLayoutTest {
public static void main(String[] args){
new InterfaceShow("Using GridLayout");

}
}

gridlayout layoutmanager

Tuesday, July 30, 2013

BorderLayout

BorderLayout lays out the components to fit the five regions of a container. These five regions are center (BorderLayout.CENTER), north (BorderLayout.NORTH), south (BorderLayout.SOUTH), east (BorderLayout.EAST), and west (BorderLayout.WEST) regions. The BorderLayout class has two constructors:
-BorderLayout()
creates a default border layout with no space between components.
-BorderLayout(int hor,int ver)
creates a border layout with spaces between components.

In the example code below, the Rotate button is placed at the north part, the Next button at the west part, the Previous button at the east part, the Zoom in and Zoom out buttons at the south part of the Frame window. The image that is displayed on the Label component is shown at the center part of the Frame window.

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.awt.Graphics;

import javax.imageio.ImageIO;
class DrawArea extends Label{

BufferedImage bi;
DrawArea(){

try{
bi=ImageIO.read(new File("d:/earth.png")); //read image file
}catch(IOException ie){}
}
public void paint(Graphics g){

g.drawImage(bi,0,0,null);
}
}

class InterfaceShow extends Frame{
InterfaceShow(String title){
setTitle(title);
setLayout(new BorderLayout());
setSize(new Dimension(500,300));
setVisible(true);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Panel p=new Panel();
p.setLayout(new FlowLayout());
Button rotatebt=new Button("Rotate");
Button zoominbt=new Button("Zoom in");
Button zoomoutbt=new Button("Zoom out");
Button movenextbt=new Button("Next");
Button movepreviousbt=new Button("Previous");
p.add(zoominbt);
p.add(zoomoutbt);
add(rotatebt,BorderLayout.NORTH);
add(movenextbt, BorderLayout.WEST);
add(movepreviousbt,BorderLayout.EAST);
add(new DrawArea(), BorderLayout.CENTER);
add(p, BorderLayout.SOUTH);
validate();
}
}
public class BorderLayoutTest{
public static void main(String[] args){
new InterfaceShow("Using BorderLayout");

}
}

borderlayout layout manager

Monday, July 29, 2013

FlowLayout

FlowLayout is one of layout managers that arranges and resizes the components placed on the window in a directional flow. The components flow  in the same way as the flow of characters in a line of text in a paragraph.

FlowLayout class has three constructors as shown below.
-FlowLayout()
creates a new flow layout with center alignment and a 5-pixcel space between the components.
-FlowLayout(int alignment)
creates a new flow layout with specified alignment. The value of the alignment can be FlowLayout.LEFT, FlowLayout.RIGHT, or FlowLayout.CENTER.
-FlowLayout(int alignment, int hor, int ver)
creates a new flow layout with specified alignment, horizontal and vertical spaces between components.

Example:
import java.awt.Button;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
InterfaceShow(String title){
setTitle(title);
setLayout(new FlowLayout(FlowLayout.LEFT));
setSize(new Dimension(500,300));

setVisible(true);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

for(int i='A';i<='Z';i++){
char c=(char)i;
add(new Button(c+""));
}

validate();
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using FlowLayout");

}
}


flowlayout layoutmanager

Sunday, July 28, 2013

Scrollbar

Scrollbar allows you to create a scrolling bar that you can select a value from a range of values. The Scrollbar  can generate adjustment event. To receive the event, the application must implement AdjustmentListener interface and register the listener by using the addAdjustmentListener(AdjustmentListener listener) method.

Constructors of Scrollbar:
-Scrollbar()
creates a new vertical scrolling bar.
-Scrollbar(int orientation)
creates a new scrolling bar with specified orientation. The orientation can be Scrollbar.HORIZONTAL or Scrollbar.VERTICAL.
-Scrollbar(int orientation, int value, int visible, int minimum, int maximum)
creates a new scrolling bar with specified orientation, initial value, visible amount, minimum and maximum values.

Useful methods of the Scrollbar class:
-getMaximum()
reads the maximum value of the scrolling bar.
-getMinimum()
reads the minimum value of the scrolling bar.
-getValue()
reads the value of the scrolling bar.
-setBlockIncrement(int v)
sets the block increment of the scrolling bar.
-setMaximum(int v)
sets the maximum value of the scrolling bar.
-setMinimum(int v)
sets the minimum value of the scrolling bar.
-setUnitIncrement(int v)
sets the unit increment of the scrolling bar.
-setValue(int v)
sets the value of the scrolling bar.

Example:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Scrollbar;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame implements AdjustmentListener{
InterfaceShow(String title){
setTitle(title);
setSize(new Dimension(500,300));
setVisible(true);
setBackground(Color.BLACK);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Scrollbar colorscroll= new Scrollbar(Scrollbar.HORIZONTAL, 0, 0, 0, 255);
colorscroll.setUnitIncrement(5);
colorscroll.setBlockIncrement(15);
colorscroll.addAdjustmentListener(this);
add(colorscroll, BorderLayout.NORTH);

}

public void adjustmentValueChanged(AdjustmentEvent e){
Scrollbar scr=(Scrollbar)e.getSource();
setBackground(new Color(scr.getValue()));

}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using ScrollBar");

}
}

scrollbar

Friday, July 26, 2013

List

List is a component that allows you to create a scrolling list of text items. You can configure the list for single or multiple selection. The List can generate item event. To receive the event, the application must implement the ItemListener and register the listener.

Constructors of the List class:
-List()
creates a new scrolling list.
-List(int rows)
creates a new scrolling list with the number of visible rows.
-List(int rows, boolean multipleMode)
creates a new scrolling list with the number of visible rows and selection mode.

Useful methods of the List class:
-add(String text)
adds text item to the end of the list.
-add(String text,int index)
adds text item to the list at the specified position.
-deselect(int index)
delects the text item at the specified index.
-getItem(int index)
gets text item at the specified index.
-getItemCount()
get the number of text items in the list.
-getItems()
gets all text items in the list.
-getSelectedItem()
gets the selected text item.
-getSelectedItems()
get all selected text items.
-isIndexSelected(int index)
determines whether or not the text item at the specified index is selected. 
-remove(int index)
removes the text item at the specified index.
-remove(String item)
removes the text item that matches the item argument.
-removeAll()
removes all text items of the list.
-select(int index)
select the text item at the specified index.
-setMultipleMode(boolean multipleMode)
sets selection mode of the list to false or true. If false, only a single text item can be selected. 

In the example program below, we construct a List component to display 15 rows of items with single item selection. If the number of items added to the List beyond this rows limit, the scroll bars are automatically attached to the list for you.  The getAllFonts method of the GraphicsEnvironment class is used to retrieve all font objects from the system. All font objects are added to the List component by using its add method.

import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Dimension;
import java.awt.GraphicsEnvironment;
import java.awt.Label;
import java.awt.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


class InterfaceShow extends Frame implements ItemListener{
Label lbl;
InterfaceShow(String title){
setTitle(title);
setSize(new Dimension(500,300));
setLayout(new FlowLayout(FlowLayout.LEFT));
setVisible(true);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
List lst=new List(15,false);
lst.addItemListener(this);
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fs=ge.getAllFonts();
for(Font f:fs){
lst.add(f.getName());
}
lbl=new Label();
add(lst);
add(lbl);
validate();
}
public void itemStateChanged(ItemEvent e){
List l=(List)e.getSource();
String text=l.getSelectedItem();
lbl.setText(text);
validate();
}

}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using List");
}
}

List awt

Thursday, July 25, 2013

Choice

Choice displays a list of items in a box in which only one item can be selected by the user. The Choice can generate item event so the application that wants to perform action when the item of the Choice is selected must implement the ItemListener interface and uses the addItemListener(ItemListener listener) method to register the listener to receive the event.

Constructor of the Choice class:
-Choice()
Useful methods of the Choice class:
-add(String text)
adds text item to the Choice box.
-getItem(int index)
reads the text item at the specified index.
-getItemCount()
counts all text items in the Choice box.
-getSelectedItem()
reads the selected item.
-insert(String text,int index)
inserts text item at the specified index.
-remove(int index)
removes the text item at the specified index.
-remove(String item)
removes the text item that matches the item argument.
-removeAll()
removes all items in the Choice box.
-select(int index)
selects the tex item at the specified index.
-select(String text)
slects the tex item that matches the item argument.

In the example code below, the Choice object, clist is created without an item. Later, its add method is used to add a list of numbers with 0 lower bound and 4999 upper bound. One of these numbers will be selected from the Choice, clist and is used as color code when constructing the color object to be used as the background color of the window.

import java.awt.Choice;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Dimension;
import java.awt.Label;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
InterfaceShow(String title){
setTitle(title);
setLayout(new FlowLayout());
setSize(new Dimension(500,300));

setVisible(true);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Label lbl=new Label("Select background color:");
Choice clist=new Choice();
for(int rgb=0;rgb<5000;rgb+=100)
clist.add(rgb+"");
clist.addItemListener(new ItemList());
add(lbl);
add(clist);
setBGColor(0);
validate();
}
public void setBGColor(int rgb){
setBackground(new Color(rgb));
}
class ItemList implements ItemListener{
public void itemStateChanged(ItemEvent e){
setBGColor(Integer.parseInt(e.getItem().toString()));
}
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using Choice");

}
}

Choice in awt

Wednesday, July 24, 2013

Checkbox vs. CheckboxGroup

With Checkbox class you are able to create a list of items that their states can be turned on or off. You can turn on or turn off multiple items. However, if you want to allow a single item to be turned on or off, you must place the checkboxes in CheckboxGroup.

The Checkbox can generate item event. To receive the item event, the application must implement ItemListener interface and uses the addItemListener(ItemListener listener) method. The ItemListener interface has itemStateChanged(ItemEvent e) that needs to be overridden to perform action when the user selects or deselect the items.

Constructors of Checkbox class:
-Checkbox()
creates a check box without label.
-Checbox(String label)
creates a check box with label.
-Checkbox(String label, boolean state)
creates a check box with label and allowing state input to turn on or turn off the check box.
-Checkbox(String label, boolean state, CheckboxGroupd group)
creates a check box with label and allowing state input to turn on or turn off the check box and specifying check box group.

Useful methods of the Checkbox class:

-getLabel():String
reads the label from the check box.
-getState():boolean
reads the state of the check box.
-setLabel(String label):void
sets the label to the check box.
-setState(boolean state):void
sets the state to the check box.



Example:

import java.awt.BorderLayout;
import java.awt.Checkbox;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
private Label lbl;
private Checkbox course1;
private Checkbox course2;
private Checkbox course3;
private Checkbox course4;

InterfaceShow(String title){
setTitle(title);
setLayout(new BorderLayout());
setSize(new Dimension(500,300));

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

course1=new Checkbox("C++",true);
course1.addItemListener(new ItemList());
course2=new Checkbox("VB.NET",false);
course2.addItemListener(new ItemList());
course3=new Checkbox("Java",true);
course3.addItemListener(new ItemList());
course4=new Checkbox("Software Engineering",false);
course4.addItemListener(new ItemList());
Panel p=new Panel();
p.setLayout(new GridLayout(5,1));
p.add(new Label("Select your favorite courses:"));
p.add(course1);
p.add(course2);
p.add(course3);
p.add(course4);
add(p, BorderLayout.NORTH);
lbl=new Label();
lbl.setForeground(Color.BLUE);
add(lbl,BorderLayout.CENTER);
setVisible(true);
validate();
}

class ItemList implements ItemListener{
public void itemStateChanged(ItemEvent e){
if(e.getSource()==course1){
lbl.setText("You have selected "+course1.getLabel());

}
else if(e.getSource()==course2){
lbl.setText("You have selected "+course2.getLabel());

}
else if(e.getSource()==course3){
lbl.setText("You have selected "+course3.getLabel());

}
else {
lbl.setText("You have selected "+course4.getLabel());
}

}
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using Checkbox and CheckboxGroup");

}
}


checkbox multiple selections


If you want to allow only a single item selection, replace part of the code:
course1=new Checkbox("C++",true);
course1.addItemListener(new ItemList());
course2=new Checkbox("VB.NET",false);
course2.addItemListener(new ItemList());
course3=new Checkbox("Java",true);
course3.addItemListener(new ItemList());
course4=new Checkbox("Software Engineering",false);
course4.addItemListener(new ItemList());

with the code:
CheckboxGroup cg=new CheckboxGroup();
course1=new Checkbox("C++",false,cg);
course1.addItemListener(new ItemList());
course2=new Checkbox("VB.NET",false,cg);
course2.addItemListener(new ItemList());
course3=new Checkbox("Java",true,cg);
course3.addItemListener(new ItemList());
course4=new Checkbox("Software Engineering",false,cg);
course4.addItemListener(new ItemList());

checkbox single selection

Tuesday, July 23, 2013

TextArea

TextArea class allows you to create a text area in which you can input and edit multiple lines of text. TextArea is able to generate text and key events as the TextField does. Its constructors and useful methods are summarized below.

Constructors of TextArea class:
-TextArea()
creates an empty text area.
-TextArea(int rows, int columns)
creates an empty text area with specifying numbers of rows and columns.
-TextArea(String text, int rows, int columns)
create a text area with default text and specifying numbers of rows and columns.

Useful methods of TextArea class:

-append(String text):void
appends text to the text area.
-getText()
reads text from the text area.
-getSelectedText()
reads selected text from the text area.
-insert(String text, int pos)
inserts text to the text area at the specified position.
-replaceRange(String text, int start,int end)
replaces a rangle of text from start to end positions with the new text specified by text argument.
-select(int start,int end)
selects text in the text area from start to end positions.
-setText(String text)
places text to the text area. The old text will be replaced.

In the example code below, we create a TextArea with 10 rows and 50 columns. To make it bigger you need to increases its row and column values. The scroll bars are automatically attached to text area when the input text reaches the rows or columns limit.

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.TextArea;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
InterfaceShow(String title){
setTitle(title);
setLayout(new FlowLayout());
setSize(new Dimension(500,300));

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

TextArea txtarea=new TextArea(10,50);
add(txtarea);

setVisible(true);
validate();
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using TextArea");

}
}


textarea awt

Sunday, July 21, 2013

TextField

TextField class allows you to create a text field to input and edit a single line of text. The TextField can generate text event and key event.

To receive text event, the application must implements TextListener interface. You will need to override the textValueChanged (TextEvent e) method of the TextListener interface to perform an action when there is any change to text in the text field. You need to use the addTextListener(TextListener listener) method to register the listener to receive the text event.

To receive key event, the application must implements KeyListener interface and register the listener.You need to use the addKeyListener (KeyListener e) method. The KeyListener interface has three methods: keyPressed(KeyEvent e), keyReleased(KeyEvent e), and keyTyped(KeyEvent e) that can be used to perform action when a key is pressed, released or typed.

Constructors of the TextField class:
-TextField()
creates an empty text field.
-TextField(int columns)
creates an empty text field with specifying the number of columns.
-TextField(String text)
creates a text field with the default text in in.
-TextField(String, int columns)
creates a text box with default text and number of columns.

Useful methods of the TextField class:
-addTextListener(TextListener listener): void
registers the text listener to receive text event from this text field.
-getText(): String
returns the text in the text field.
-setEchoChar(char c):void
sets the echo character for this text field.
-setEditable(boolean editable): void
determines whether or not the text field is editable.


Example: text field with text event

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
private Label lbl;
private TextField txtname;
InterfaceShow(String title){
setTitle(title);
setLayout(new FlowLayout(FlowLayout.CENTER));
//setExtendedState(Frame.MAXIMIZED_BOTH);
setSize(new Dimension(300,200));
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
txtname=new TextField(30);
txtname.addTextListener(new TextList());
lbl=new Label();
lbl.setFont(new Font("Arial",Font.BOLD,30));
add(txtname);
add(lbl);

setVisible(true);
validate();
}

class TextList implements TextListener{
public void textValueChanged(TextEvent e){
lbl.setText(txtname.getText());
validate();
}
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using TextField");

}
}


textfield with text event textlistener


For another example, the text field object is used with the KeyListener interface. To allow only number digits, you need to track the code of character input in the keyTyped method. The digit characters are from 0 to 9 and their equivalent codes are from 48 to 57. The consume method of the KeyEvent class is used to hide an undesirable character.

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
private Label lbl;
private TextField txtname;
InterfaceShow(String title){
setTitle(title);
setLayout(new FlowLayout(FlowLayout.CENTER));
//setExtendedState(Frame.MAXIMIZED_BOTH);
setSize(new Dimension(300,200));
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
txtname=new TextField(30);
txtname.addKeyListener(new KeyList());
lbl=new Label("Enter a number:");
add(lbl);
add(txtname);
setVisible(true);
validate();
}

class KeyList implements KeyListener{
public void keyTyped(KeyEvent e){
int intkey=e.getKeyChar();
if(!(intkey>=48 && intkey<=57))
e.consume();
}
public void keyPressed(KeyEvent e){

}
public void keyReleased(KeyEvent e){

}

}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using TextField");

}
}


text field with key event keylistener

Saturday, July 20, 2013

Button

Button is a component class in AWT package. When a button is pushed, an action can happen. An application that wants to perform some action when the button is pushed has to implement ActionLister interface and registers the new listener to receive events from the button by calling the addActionListener(ActionListener listener) method. The code to perform actions when the button is pushed will be placed in the actionPerformed(ActionEvent e) method of the ActionLister interface.

Constructors of Button class:
-Button()
creates a button with empty label.
-Button(String label)
creates a button with string label.
Useful methods of Button class:
-addActionListener(ActionListener listener): void
registers the new listener to receive events from the button.
-getLabel(): String
reads the label on the button.
-setLabel(String label): void
  set the label to the button.

Example:

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
class ShowImage extends Label{
BufferedImage bi=null;
public void paint(Graphics g){
if(bi!=null)
g.drawImage(bi,0,0,null);
}

public void loadImage(String filename){
try{
bi=ImageIO.read(new File(filename));
}catch(IOException ie){System.out.println("Can't read the image file");}
}
}

class InterfaceShow extends Frame implements ActionListener{
InterfaceShow(String title){
setTitle(title);
setSize(new Dimension(350,300));
setLayout(new BorderLayout());
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Button btshow=new Button("Show image");
btshow.addActionListener(this);
Panel panel=new Panel();
panel.add(btshow);
add(panel, BorderLayout.NORTH);
setVisible(true);

}

public void actionPerformed(ActionEvent e){
ShowImage si=new ShowImage();
si.loadImage("d:/earth.png");
add(si,BorderLayout.CENTER);
validate();

}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using Button");

}
}
button java

Label

Label is a component in AWT package. It is used to display non-editable text on the window. You can create a label by using the Label class. The Label class is summarized below.

Label constructors:
-Label()
creates a label object without any text on it.
-Label(String text)
creates a label object with text on it.
-Label(String text,int alignment)
creates a label object with text on it and the text alignment is specified.

Useful fields of the Label class:
-CENTER
-LEFT
-RIGHT
Useful methods of the Label class:
-getText()
reads text from the label object.
-setAlignment(int alignment)
sets the text alignment of the label object.
-setText(String text)
sets the text of the label object.
-setForeground(Color color)
sets the text color the label object.
-setFont(Font font)
sets the font of text of the label object.

Example:
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

class InterfaceShow extends Frame{
InterfaceShow(String title){
setTitle(title);
setSize(new Dimension(500,300));

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

Label lbl=new Label();
Lbl.setText("This is the text placed on the Label.");
lbl.setFont(new Font("Arial",Font.BOLD,20));
lbl.setAlignment(Label.CENTER);
add(lbl);
setVisible(true);
validate();
}
}
public class AWTControls {
public static void main(String[] args){
new InterfaceShow("Using Label");

}
}

Label in awt

In the example code about, a label object called lbl is created without specifying its text and with the default alignment. The the setText method is used to set the text of the label. Its setFont method is used to set a font object to text of the label. The syntax to create a font object is Font f=new Font(Font_name, Font_style, Font_size). To specify that the text of the label must be left aligned, you need to use the setAlignment method. This method accepts a constant value Label.LEFT, Label.RIGHT, or Label.CENTER. If you supply Label.LEFT to this method, the text of the label will be left aligned. By supplying Label.RIGHT, the text is right aligned and so son.

BufferedImage to byte array

Sometimes it is worth to convert from a buffered image object to an array of bytes for later use in your program. You can do this by using the write(BufferedImage bi,String type,OutputStream os) method of the ImageIO class. See the example code below:

public void BufferedImageToByteArray(String filename){
try{

BufferedImage orImage=ImageIO.read(new File(filename));
ByteArrayOutputStream baos=new ByteArrayOutputStream();
ImageIO.write(orImage, "jpg", baos );
byte[] imageBytes=baos.toByteArray();
//do something with the byte array

}catch(IOException ie){}
}


In the example above, the data of an image is read by using the read method of the ImageIO class. This image data is stored in the orImage, BufferedImage object variable. The ByteArrayOutputStream object is constructed so it is ready to accept the image data. The write method of the ImageIO class is used to write or transfer the data to the ByteArrayOutputStream object. The ByteArrayOutputStream has a method call toByteArray that can return the image data in an array of bytes.

If you would like to convert back from the byte array to an buffered image object, you need to use the ByteArrayIntputStream class to read the byte array in to the ByteArrayIntputStream object. Then use the read(InputStream) method of the ImageIO to return a buffered image object.

ByteArrayInputStream bais=new ByteArrayInputStream(imageBytes);
BufferedImage bi=ImageIO.read(bais);
compass app flashLight app

BufferedImage to Image

Sometimes you might want to convert from BufferedImage object to Image object. This task can be done by using the createImage(ImageProducer producer) method of any component. A class that implements the ImageProducer interface is FilteredImageSource. Its constructor is FilteredImageSource(ImageProducer producer, ImageFilter filter). RGBImageFilter is a class that implements the ImageFilter interface. This class has a method called filterRGB that can be override to filter rgb color of the image.  In the example below, the createImage method is used to create an image object based on the image data source and the image filter. Since, we do not want to change the color of original image, the filterRGB method simply returns rgb value. By returning the rgb value, you can make sure that there is no change from the source to the destination image.

public void BufferedImageToImage(String filename){
ImageFilter filter = new RGBImageFilter() {
  public final int filterRGB(int x, int y, int rgb) {
        return rgb; //nothing change to the image    
    }
  };

try{
  BufferedImage srcimg=ImageIO.read(new File(filename));
      Image img = createImage(new FilteredImageSource(srcimg.getSource(),filter));
      //do something with the image object img

}catch(Exception e){e.printStackTrace();}
}

Image to BufferedImage

In general, image manipulation is performed on the BufferedImage object. So it is useful to convert from image object to buffered image object. In Java, when you have an image object, there are two ways to convert it to the buffered image object.

One way is using the read(File file) method of the ImageIO class. See the example code below:
public void ImageToBufferedImage(String filename){
try{

BufferedImage bi=ImageIO.read(new File(filename));
//do something with the buffered image bi

}catch(IOException ie){}
}

Alternatively, you can create a blank buffered image object then draw the image on this buffered image object. See the example code below:

public void createImage(String imgfile){

BufferedImage bi=new BufferedImage(500,300, BufferedImage.TYPE_INT_ARGB);
Image img=Toolkit.getDefaultToolkit().getImage("d:/earth.png");
MediaTracker mt=new MediaTracker(this);
mt.addImage(img, 0);
try{
mt.waitForID(0);
}catch(InterruptedException e){}
Graphics2D g2d=bi.createGraphics();
g2d.drawImage(img,0,0,null);

//do something with the buffered image bi
}

Font

Font class represents fonts of text to display on a component. When constructing a new font object, you need to specify font name (logical name), style, and font size.

Font constructor:
-Font(String fontname,int style, int size)
Useful fields:
-BOLD
-ITALIC
-PLAIN
Useful methods:
-getName():String
-getSize():int
-getStyle():int
-isBold():boolean
-isItalic():boolean
-isPlain():boolean

In the example below, a new Tahoma font with Bold style, and 30 in size is created. To apply the font to the text to be drawn on the Canvas, you need to the setFont(Font font) method by supplying the created font to this method argument.

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.ImageObserver;

class DrawArea extends Canvas implements ImageObserver{
public void paint(Graphics g){

Font f=new Font("Tahoma",Font.BOLD,30);
g.setFont(f);
g.drawString("Hello, World!", 300,100);


}
}
class WindowShow extends Frame{
public WindowShow(String title){
setTitle(title);
setSize(600,400);
setVisible(true);
add(new DrawArea());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
}
public class AWTTEST {
public static void main(String[] args){

new WindowShow("Using font");

}


}


List all font in the system

To get all fonts in the system, you can use the getAllFonts() method of the GraphicsEnvironment class.

Example:
public static void showFonts(){
GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
Font[] fonts=ge.getAllFonts();
for(Font f:fonts){
System.out.println(f.getName());
}
}

Graphics2D

Graphics2D is the derived class of the base class Graphics. While Graphics class provides the basics for graphical contexts, the Graphics2D allows you to do sophisticated things in drawing. For example, by using the Graphics2D class you can rotate coordinates, and apply different styles and colors to text and shapes.
Graphics2D is also an abstract class. Its useful methods are shown below.

-clip(Shape sp):void
intersects the current drawing area or clip with the interior of specified shape. The result is the intersection area.
-draw(Shape sp):void
draws the specified shape object.
-drawImage(BufferedImage bi, BufferedImageOp filter, int x,int y): void
draws a BufferedImage object that is filtered with BufferedImageOp.
-drawImage(Image img, AffineTransform af, ImageObserver observer): void
draw an Image object with the transformation specified by AffineTransformed object.
-fill(Shape sp):void
renders a shape that its interior is filled with a default (black color) or specified color, or painting style (GradientPaint, LinearGradientPaint, or TexturePaint).
-rotate(double theta):void
rotate x and y axes of the coordinate system.
-scale(double sx,double sy):void
resizes a shape or an image according to the scaling factors.
-setPaint(Paint paint):void
applies a Paint object to the graphical context.
-setStroke(Stroke stroke):void
applies a Stroke object to the graphical context.
-setTranform(AffineTransform af):void
applies the transformation to the graphical context.
-translate(int x,int y):void
moves the origin to the specified coordinate.


Example 1: draw different shapes

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.RoundRectangle2D;

import javax.imageio.ImageIO;

class DrawArea extends Canvas{
public void paint(Graphics g){

Graphics2D g2d=(Graphics2D)g;
g2d.draw(new RoundRectangle2D.Double(10, 50, 100, 100,10,10)); //draw a

round rectangle
g2d.draw(new Ellipse2D.Double(10, 200, 100, 100)); //draw an ellipse

}
}
class WindowShow extends Frame{
public WindowShow(String title){
setTitle(title);
setSize(600,400);
setVisible(true);
add(new DrawArea());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
}
public class AWTTEST {
public static void main(String[] args){

new WindowShow("Draw shapes with Graphics2D");

}


}


draw shapes graphics2d


Example 2: fill shapes with different colors

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Arc2D;
import java.awt.geom.Ellipse2D.Double;

class DrawArea extends Canvas{
public void paint(Graphics g){

Graphics2D g2d=(Graphics2D)g;
g2d.setPaint(Color.GREEN);
g2d.fill(new Ellipse2D.Double(20,50,200,200)); //fill an ellipse with

the green color
g2d.setPaint(Color.RED);
g2d.fill(new Arc2D.Double(20,300,200,200,0,180,Arc2D.PIE)); //fill an

arc with the red color



}
}
class WindowShow extends Frame{
public WindowShow(String title){
setTitle(title);
setSize(600,400);
setVisible(true);
add(new DrawArea());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
}
public class AWTTEST {
public static void main(String[] args){
new WindowShow("Fill shapes");

}

}


fill shapes with color graphics2d


Example 3: fill an ellipse with the gradient style


import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Ellipse2D;


class DrawArea extends Canvas{
public void paint(Graphics g){

Graphics2D g2d=(Graphics2D)g;
GradientPaint gp=new GradientPaint(100,100, Color.RED, 150,200,

Color.BLUE); //create GradientPaint object
g2d.setPaint(gp); //apply the GradientPaint object to the graphical

context
g2d.fill(new Ellipse2D.Double(20,50,200,200)); //fill an ellipse


}
}
class WindowShow extends Frame{
public WindowShow(String title){
setTitle(title);
setSize(600,400);
setVisible(true);
add(new DrawArea());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
}
public class AWTTEST {
public static void main(String[] args){
new WindowShow("Fill ellipse with gradient style");

}


}


fill shapes with gradient style graphics2d


Example 4: fill a rectangle with images by using TexturePaint

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

class DrawArea extends Canvas{
public void paint(Graphics g){

Graphics2D g2d=(Graphics2D)g;
try{
BufferedImage bi=ImageIO.read(new File("d:/earth.png"));
TexturePaint tp=new TexturePaint(bi,new Rectangle2D.Double

(100,100,40,40));
g2d.setPaint(tp);
g2d.fill(new Rectangle2D.Double(100, 100, 200, 200));

}catch(IOException e){}


}
}
class WindowShow extends Frame{
public WindowShow(String title){
setTitle(title);
setSize(600,400);
setVisible(true);
add(new DrawArea());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
}
public class AWTTEST {
public static void main(String[] args){

new WindowShow("Fill shape with TexturePaint");

}
}


fill shapes with texturepaint graphics2d


Example 5: rotate an image

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.ImageObserver;

class DrawArea extends Canvas implements ImageObserver{
public void paint(Graphics g){
Graphics2D g2d=(Graphics2D)g;
Image img=Toolkit.getDefaultToolkit().getImage("d:/image02.png");
g2d.translate(300, 0); //move from origin to coordinate (300,0)
g2d.rotate(Math.PI/2); //rotate the image by Math.PI/2(=1.57)
g2d.drawImage(img, 0, 0,img.getWidth(this), img.getHeight(this),this);


}
}
class WindowShow extends Frame{
public WindowShow(String title){
setTitle(title);
setSize(600,400);
setVisible(true);
add(new DrawArea());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
}
public class AWTTEST {
public static void main(String[] args){
new WindowShow("Image rotation");

}
}


rotate image graphics2d


Example 6: make an image gray

import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

class DrawArea extends Canvas{
public void paint(Graphics g){

Graphics2D g2d=(Graphics2D)g;
ColorConvertOp op=new ColorConvertOp(ColorSpace.getInstance

(ColorSpace.CS_GRAY), new RenderingHints(null)); //create gray color filter object to

apply to the image
try{

BufferedImage bi=ImageIO.read(new File("d:/myprogram/image02.png"));

//create BufferedImage object to encapsulate the image
g2d.drawImage(bi,op,20,50); //show the image

}catch(IOException e){}


}
}

class WindowShow extends Frame{
public WindowShow(String title){
setTitle(title);
setSize(600,400);
setVisible(true);
add(new DrawArea());

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

}
}
public class AWTTEST {
public static void main(String[] args){

new WindowShow("Making an image gray");

}

}



Example 7: make an image brighter

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;

class DrawArea extends Canvas{
Image img;
DrawArea(){
//create MediaTracker to control the image load
MediaTracker mt=new MediaTracker(this);
//read image file
img=Toolkit.getDefaultToolkit().getImage("d:/myprogram/image02.png");
mt.addImage(img,0); //add image to the tracker
try{
mt.waitForID(0); //wait the image load
}catch(InterruptedException ie){}
}
public void paint(Graphics g){

Graphics2D g2d=(Graphics2D)g;
BufferedImage bi=makeBrighter(img);
g2d.drawImage(bi,0,0,bi.getWidth(),bi.getHeight(),null);


}
public BufferedImage makeBrighter(Image img){

BufferedImage bi=new BufferedImage(img.getWidth

(null),img.getHeight(null),BufferedImage.TYPE_INT_ARGB);
BufferedImage resultimg=new BufferedImage(img.getWidth

(null),img.getHeight(null),BufferedImage.TYPE_INT_ARGB);
float[] elements = {0.0f, 1.0f, 0.0f, -

1.0f,1.0f,1.0f,0.0f,0.0f,0.0f};
Kernel kernel = new Kernel(3, 3, elements);  //create

kernel object to encapsulate the elements array
ConvolveOp op = new ConvolveOp(kernel,

ConvolveOp.EDGE_NO_OP, null); //create ConvolveOp filter object
Graphics2D graphics2d=bi.createGraphics();
graphics2d.drawImage(img,0,0,bi.getWidth(),bi.getHeight

(),null);
op.filter(bi,resultimg);
return resultimg;
}
}
class WindowShow extends Frame{
public WindowShow(String title){
setTitle(title);
setSize(800,600);
setVisible(true);
DrawArea da=new DrawArea();
add(da);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

validate();

}

}
public class AWTTEST {
public static void main(String[] args){

new WindowShow("Make image brighter");

}

}




Example 8: resize an image

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;

class DrawArea extends Canvas{
Image img;
DrawArea(){

//create MediaTracker to control the image load
MediaTracker mt=new MediaTracker(this);
//read image file
img=Toolkit.getDefaultToolkit().getImage("d:/myprogram/image02.png");
mt.addImage(img,0); //add image to the tracker
try{
mt.waitForID(0); //wait the image load
}catch(InterruptedException ie){}
}
public void paint(Graphics g){

Graphics2D g2d=(Graphics2D)g;
//resize image: new width=original width multiplied by 1.2
//new height=original height multiplied by 1.2
g2d.scale(1.2, 1.2);
//display the resized image
g2d.drawImage(img,0,0,null);

}

}
class WindowShow extends Frame{
public WindowShow(String title){
setTitle(title);
setSize(800,600);
setVisible(true);
DrawArea da=new DrawArea();
add(da);

addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});

validate();

}

}
public class AWTTEST {
public static void main(String[] args){

new WindowShow("Resizing an image");

}

}