You are on page 1of 44

Java AWT Tutorial

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-


based applications in java.

Java AWT components are platform-dependent i.e. components are


displayed according to the view of operating system. AWT is heavyweight
i.e. its components are using the resources of OS.

The java.awt package provides classes for AWT api such


as TextField, Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.


Container

The Container is a component in AWT that can contain another components


like buttons, textfields, labels etc. The classes that extends Container class
are known as container such as Frame, Dialog and Panel.

Window

The window is the container that have no borders and menu bars. You must
use frame, dialog or another window for creating a window.

Panel

The Panel is the container that doesn't contain title bar and menu bars. It
can have other components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It
can have other components like button, textfield etc.

Useful Methods of Component class

Method Description

public void add(Component inserts a component on this


c) component.

public void setSize(int sets the size (width and height) of the
width,int height) component.

public void defines the layout manager for the


setLayout(LayoutManager component.
m)

public void changes the visibility of the


setVisible(boolean status) component, by default false.

Java AWT Example

To create simple awt example, you need a frame. There are two ways to
create a frame in AWT.

o By extending Frame class (inheritance)


o By creating the object of Frame class (association)

AWT Example by Inheritance

Let's see a simple example of AWT where we are inheriting Frame class.
Here, we are showing Button component on the Frame.

1. import java.awt.*;  
2. class First extends Frame{  
3. First(){  
4. Button b=new Button("click me");  
5. b.setBounds(30,100,80,30);// setting button position  
6. add(b);//adding button into frame  
7. setSize(300,300);//frame size 300 width and 300 height  
8. setLayout(null);//no layout manager  
9. setVisible(true);//now frame will be visible, by default not visible  
10. }  
11. public static void main(String args[]){  
12. First f=new First();  
13. }}  
The setBounds(int xaxis, int yaxis, int width, int height) method is used in
the above example that sets the position of the awt button.
AWT Example by Association
Let's see a simple example of AWT where we are creating instance of Frame class. Here, we
are showing Button component on the Frame.

1. import java.awt.*;  
2. class First2{  
3. First2(){  
4. Frame f=new Frame();  
5. Button b=new Button("click me");  
6. b.setBounds(30,50,80,30);  
7. f.add(b);  
8. f.setSize(300,300);  
9. f.setLayout(null);  
10. f.setVisible(true);  
11. }  
12. public static void main(String args[]){  
13. First2 f=new First2();  
14. }}  

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on button,
dragging mouse etc. The java.awt.event package provides many event classes and
Listener interfaces for event handling.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:

1. Register the component with the Listener

Registration Methods
For registering the component with the Listener, many classes provide the registration
methods. For example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

Java Event Handling Code


We can put the event handling code into one of the following
places:
1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener


import java.awt.*;  
import java.awt.event.*;  
class AEvent extends Frame implements ActionListener{  
TextField tf;  
AEvent(){  
 
//create components  
tf=new TextField();  
tf.setBounds(60,50,170,20);  
Button b=new Button("click me");  
b.setBounds(100,120,80,30);  
  
//register listener  
b.addActionListener(this);//passing current instance  
  
//add components and set size, layout and visibility  
add(b);add(tf);  
setSize(300,300);  
setLayout(null);  
setVisible(true);  
}  
public void actionPerformed(ActionEvent e){  
tf.setText("Welcome");  
}  
public static void main(String args[]){  
new AEvent();  
}  

public void setBounds(int xaxis, int yaxis, int width, int height); have been used in
the above example that sets the position of the component it may be button, textfield etc.

 Java event handling by outer class


import java.awt.*;  
import java.awt.event.*;  
class AEvent2 extends Frame{  
TextField tf;  
AEvent2(){  
//create components  
tf=new TextField();  
tf.setBounds(60,50,170,20);  
Button b=new Button("click me");  
b.setBounds(100,120,80,30);  
//register listener  
Outer o=new Outer(this);  
b.addActionListener(o);//passing outer class instance  
//add components and set size, layout and visibility  
add(b);add(tf);  
setSize(300,300);  
setLayout(null);  
setVisible(true);  
}  
public static void main(String args[]){  
new AEvent2();  
}  
}  

import java.awt.event.*;  
class Outer implements ActionListener{  
AEvent2 obj;  
Outer(AEvent2 obj){  
this.obj=obj;  
}  
public void actionPerformed(ActionEvent e){  
obj.tf.setText("welcome");  
}  
}  

Java event handling by anonymous class


import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);

b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
}
}

Java AWT Button


The button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.

AWT Button Class declaration


public class Button extends Component implements Accessible  

Java AWT Button Example


import java.awt.*;  
public class ButtonExample {  
public static void main(String[] args) {  
    Frame f=new Frame("Button Example");  
    Button b=new Button("Click Here");  
    b.setBounds(50,100,80,30);  
    f.add(b);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  
}  
Output:

Java AWT Button Example with ActionListener


import java.awt.*;  
import java.awt.event.*;  
public class ButtonExample {  
public static void main(String[] args) {  
    Frame f=new Frame("Button Example");  
    final TextField tf=new TextField();  
    tf.setBounds(50,50, 150,20);  
    Button b=new Button("Click Here");  
    b.setBounds(50,100,60,30);  
    b.addActionListener(new ActionListener(){  
    public void actionPerformed(ActionEvent e){  
            tf.setText("Welcome to Javatpoint.");  
        }  
    });  
    f.add(b);f.add(tf);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);   
}  
}  
Output:

Java AWT Label


The object of Label class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly.

AWT Label Class Declaration


public class Label extends Component implements Accessible  

Java Label Example


import java.awt.*;  
class LabelExample{  
public static void main(String args[]){  
    Frame f= new Frame("Label Example");  
    Label l1,l2;  
    l1=new Label("First Label.");  
    l1.setBounds(50,100, 100,30);  
    l2=new Label("Second Label.");  
    l2.setBounds(50,150, 100,30);  
    f.add(l1); f.add(l2);  
    f.setSize(400,400);  
    f.setLayout(null);  
    f.setVisible(true);  
}  
}  
Output:

Java AWT Label Example with ActionListener


import java.awt.*;
import java.awt.event.*;
public class LabelExample extends Frame implements ActionListener{
TextField tf; Label l; Button b;
LabelExample(){
tf=new TextField();
tf.setBounds(50,50, 150,20);
l=new Label();
l.setBounds(50,100, 250,20);
b=new Button("Find IP");
b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
}
}
Output:

Java AWT TextField


The object of a TextField class is a text component that allows the editing of a single line
text. It inherits TextComponent class.

AWT TextField Class Declaration


public class TextField extends TextComponent

Java AWT TextField Example


import java.awt.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new TextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
Java AWT TextField Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class TextFieldExample extends Frame implements ActionListener{
TextField tf1,tf2,tf3;
Button b1,b2;
TextFieldExample(){
tf1=new TextField();
tf1.setBounds(50,50,150,20);
tf2=new TextField();
tf2.setBounds(50,100,150,20);
tf3=new TextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,200,50,50);
b2=new Button("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
add(tf1);add(tf2);add(tf3);add(b1);add(b2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}
}
Output:

Java AWT TextArea


The object of a TextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits TextComponent class.

AWT TextArea Class Declaration


public class TextArea extends TextComponent

Java AWT TextArea Example


import java.awt.*;
public class TextAreaExample
{
TextAreaExample(){
Frame f= new Frame();
TextArea area=new TextArea("Welcome to javatpoint");
area.setBounds(10,30, 300,300);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample();
}
}
Output:
Java AWT TextArea Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class TextAreaExample extends Frame implements ActionListener{
Label l1,l2;
TextArea area;
Button b;
TextAreaExample(){
l1=new Label();
l1.setBounds(50,50,100,30);
l2=new Label();
l2.setBounds(160,50,100,30);
area=new TextArea();
area.setBounds(20,100,300,300);
b=new Button("Count Words");
b.setBounds(100,400,100,30);
b.addActionListener(this);
add(l1);add(l2);add(area);add(b);
setSize(400,450);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}
Output:
Java AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on (true)
or off (false). Clicking on a Checkbox changes its state from "on" to "off" or from "off" to
"on".

AWT Checkbox Class Declaration


public class Checkbox extends Component implements ItemSelectable, Accessible

Java AWT Checkbox Example


import java.awt.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
Output:
Java AWT Checkbox Example with ItemListener
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("CheckBox Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
Output:

Java AWT CheckboxGroup


The object of CheckboxGroup class is used to group together a set of Checkbox. At a
time only one check box button is allowed to be in "on" state and remaining check box
button in "off" state. It inherits the object class.

Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special
control for creating radio buttons in AWT.
AWT CheckboxGroup Class Declaration
public class CheckboxGroup extends Object implements Serializable

Java AWT CheckboxGroup Example


import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
Output:

Java AWT CheckboxGroup Example with


ItemListener
import java.awt.*;
import java.awt.event.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, false);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1); f.add(checkBox2); f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
checkBox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ checkbox: Checked");
}
});
checkBox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java checkbox: Checked");
}
});
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
Output:

Java AWT Choice


The object of Choice class is used to show popup menu of choices. Choice selected by
user is shown on the top of a menu. It inherits Component class.

AWT Choice Class Declaration


public class Choice extends Component implements ItemSelectable, Accessible
Java AWT Choice Example
import java.awt.*;
public class ChoiceExample
{
ChoiceExample(){
Frame f= new Frame();
Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ChoiceExample();
}
}
Output:

Java AWT Choice Example with ActionListener


import java.awt.*;
import java.awt.event.*;
public class ChoiceExample
{
ChoiceExample(){
Frame f= new Frame();
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Button b=new Button("Show");
b.setBounds(200,100,50,20);
final Choice c=new Choice();
c.setBounds(100,100, 75,75);
c.add("C");
c.add("C++");
c.add("Java");
c.add("PHP");
c.add("Android");
f.add(c);f.add(label); f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+
c.getItem(c.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String args[])
{
new ChoiceExample();
}
}
Output:

Java AWT List


The object of List class represents a list of text items. By the help of list, user can
choose either one item or multiple items. It inherits Component class.

AWT List class Declaration


public class List extends Component implements ItemSelectable, Accessible
Java AWT List Example
import java.awt.*;
public class ListExample
{
ListExample(){
Frame f= new Frame();
List l1=new List(5);
l1.setBounds(100,100, 75,75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}
Output:
Java AWT List Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class ListExample
{
ListExample(){
Frame f= new Frame();
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(500,100);
Button b=new Button("Show");
b.setBounds(200,150,80,30);
final List l1=new List(4, false);
l1.setBounds(100,100, 70,70);
l1.add("C");
l1.add("C++");
l1.add("Java");
l1.add("PHP");
final List l2=new List(4, true);
l2.setBounds(100,200, 70,70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
l2.add("CodeIgniter");
f.add(l1); f.add(l2); f.add(label); f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected:
"+l1.getItem(l1.getSelectedIndex());
data += ", Framework Selected:";
for(String frame:l2.getSelectedItems()){
data += frame + " ";
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample();
}
}
Output:

SWING JFrame basics, how to create JFrame


This tutorial explains JFrame basics from creation to customization.

What is JFrame?
JFrame is a class of javax.swing package extended by java.awt.frame, it adds support for
JFC/SWING component architecture. It is the top level window, with border and a title bar.
JFrame class has many methods which can be used to customize it.

Creating a JFrame
JFrame class has many constructors used to create a JFrame. Following is the description.

JFrame(): creates a frame which is invisible


JFrame(GraphicsConfiguration gc): creates a frame with a blank title and graphics
configuration of screen device.
JFrame(String title): creates a JFrame with a title.
JFrame(String title, GraphicsConfiguration gc): creates a JFrame with specific Graphics
configuration and specified title.
Here is a simplest example just to create a JFrame.

1. package Example;
2.
3. import java.awt.GraphicsConfiguration;
4.
5. import javax.swing.JFrame;
6.
7. public class JFrameExample {
8.
9. static GraphicsConfiguration gc;
10. public static void main(String[] args){
11. JFrame frame= new JFrame(gc);
12. frame.setVisible(true);
13. }
14. }
Here is how it will display

JFrame
Set title of JFrame
To set title of a JFrame, you can use JFrame.setTitle(String title).

Here is the code

1. package Example;
2.
3. import java.awt.GraphicsConfiguration;
4.
5. import javax.swing.JFrame;
6.
7. public class JFrameExample {
8.
9. static GraphicsConfiguration gc;
10. public static void main(String[] args){
11. JFrame frame= new JFrame(gc);
12. frame.setTitle("Welecome to JavaTutorial.net");
13. frame.setVisible(true);
14. }
15. }
Here how it looks
Set title of a JFrame
Change window size of a JFrame
To resize a frame, JFrame provides a method JFrame.setSize(int width, int height), it takes
two parameters width and height. Here is how code looks now

1. package Example;
2.
3. import java.awt.GraphicsConfiguration;
4.
5. import javax.swing.JFrame;
6.
7. public class JFrameExample {
8.
9. static GraphicsConfiguration gc;
10. public static void main(String[] args){
11. JFrame frame= new JFrame(gc);
12. frame.setTitle("Welecome to JavaTutorial.net");
13. frame.setSize(600, 400);
14. frame.setVisible(true);
15. }
16. }

Resize a JFrame
After setting size of a JFrame you will notice you can still change it size by just simply
putting the cursor at the corners and dragging it. Or if you press resize option next to close
at the top right corner, it will maximize to the size of full screen. This happens because
resize is set true by default. You can simply make false as

JFrame.setResizable(false), now it will appear according to the dimensions you have given
in code and will not resize by the graphical interface.

Change position on the screen


To change position of JFrame on screen JFranme provides a method
JFrame.setlocation(int x, int y), it takes two paramters x represents position along x-axis
and y represents position along y-axis. The top left corner of your screen is (0,0).

Closing a JFrame
You can easily close your JFrame by clicking on the X(cross) at the top left corner of
JFrame. However JFrame.setDefaultCloseOperation(int) is a method provided by JFrmae
class, you can set the operation that will happen when user clicks on cross. If “0” is given as
a parameter, JFrame will not close even after clicking on cross.

The best practice is to use JFrame.EXIT_ON_CLOSE, it exits application (JFrame) and


releases memory.

JFrame.HIDE_ON_CLOSE: It doesnot close JFrame, simply hides it.

JFrame.DISPOSE_ON_CLOSE: It dispose the frame off, but it keeps running and


consumes memory.

JFrame.DO_NOTHING_ON_CLOSE: It does nothing when user clicks on close.

Here’s how the final code looks like

1. package Example;
2.
3. import java.awt.GraphicsConfiguration;
4.
5. import javax.swing.JFrame;
6.
7. public class JFrameExample {
8.
9. static GraphicsConfiguration gc;
10. public static void main(String[] args){
11. JFrame frame= new JFrame(gc);
12. frame.setTitle("Welecome to JavaTutorial.net");
13. frame.setSize(600, 400);
14. frame.setLocation(200, 200);
15. frame.setVisible(true);
16. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. frame.setResizable(false);
18. }
19. }

Java SWING JFrame Layouts Example


This tutorial explains various JFrmae layouts with examples and use.
Explanation
Java AWT package provides many different layouts for example, border layout, box Layout,
flow layout, grid layout etc. These layout managers are used to arrange the components in
particular manner. Layouts are used to manage components in a specific order. Following is
the description and examples of few common used layouts in Java.

Border Layout
Border layout is one of the most common used layouts. It is the default layout in JFrame. It
can position components in five different regions like top, bottom, left, right and center. In
border layout each region contain only one component. All free space is placed in the
center.

Use: Initialize content pane with border layout and add components to it by add method and
give layout as a parameter.

Following example shows component arranged in border layout.

1. package javatutorial.net;
2. import java.awt.BorderLayout;
3.
4. import javax.swing.JButton;
5. import javax.swing.JFrame;
6.
7. public class BorderLayoutExample {
8.
9. BorderLayoutExample(){
10. JFrame frame = new JFrame("Border Layout");
11. JButton button,button1, button2, button3,button4;
12. button = new JButton("left");
13. button1 = new JButton("right");
14. button2 = new JButton("top");
15. button3 = new JButton("bottom");
16. button4 = new JButton("center");
17. frame.add(button,BorderLayout.WEST);
18. frame.add(button1, BorderLayout.EAST);
19. frame.add(button2, BorderLayout.NORTH);
20. frame.add(button3, BorderLayout.SOUTH);
21. frame.add(button4, BorderLayout.CENTER);
22.
23. frame.setSize(300,300);
24. frame.setVisible(true);
25. }
26.
27. public static void main(String[] args){
28. new BorderLayoutExample();
29. }
30. }
Here is the output of border layout
Border Layout
Flow Layout
Flow layout is the common used layout. It is default layout used by JPanel. It is used to
arrange components in a line or a row for example from left to right or from right to left. It
arranges components in a line, if no space left remaining components goes to next line.
Align property determines alignment of the components as left, right, center etc.

Use: Set JFrame layout by using JFrame.setLayout(layout), pass flow layout as a


parameter.

Following example shows components arranged in flow layout

1. package javatutorial.net;
2.
3. import java.awt.BorderLayout;
4. import java.awt.FlowLayout;
5.
6. import javax.swing.JButton;
7. import javax.swing.JFrame;
8.
9. public class FlowLayoutExample {
10.
11. FlowLayoutExample(){
12. JFrame frame = new JFrame("Flow Layout");
13. JButton button,button1, button2, button3,button4;
14. button = new JButton("button 1");
15. button1 = new JButton("button 2");
16. button2 = new JButton("button 3");
17. button3 = new JButton("button 4");
18. button4 = new JButton("button 5");
19. frame.add(button);
20. frame.add(button1);
21. frame.add(button2);
22. frame.add(button3);
23. frame.add(button4);
24. frame.setLayout(new FlowLayout());
25. frame.setSize(300,300);
26. frame.setVisible(true);
27.
28. }
29. public static void main(String[] args) {
30. new FlowLayoutExample();
31.
32. }
33.
34. }
Here is an example of flow layout

Flow Layout
Grid Layout
Grid layout arranges component in rectangular grid. It arranges component in cells and
each cell has the same size. Components are placed in columns and rows. GridLayout(int
rows, int columns) takes two parameters that is column are row.

Use: Set JFrame layout by using JFrame.setLayout(layout), pass grid layout as a


parameter.

Following example shows components arranged in grid layout (with 2 rows and 3 columns).

1. package javatutorial.net;
2. import java.awt.GridLayout;
3. import javax.swing.JButton;
4. import javax.swing.JFrame;
5.
6. public class gridLayoutExample {
7.
8. gridLayoutExample(){
9. JFrame frame = new JFrame("Flow Layout");
10. JButton button,button1, button2, button3,button4;
11. button = new JButton("button 1");
12. button1 = new JButton("button 2");
13. button2 = new JButton("button 3");
14. button3 = new JButton("button 4");
15. button4 = new JButton("button 5");
16. frame.add(button);
17. frame.add(button1);
18. frame.add(button2);
19. frame.add(button3);
20. frame.add(button4);
21. frame.setLayout(new GridLayout(2,3));
22. frame.setSize(300,300);
23. frame.setVisible(true);
24.
25. }
26. public static void main(String[] args) {
27. new gridLayoutExample();
28.
29. }
30.
31. }
Here is the output of grid layout

Grid Layout
Interact with JFrame – buttons, listeners and
text fields
This tutorial explains how you can interact with JFrame by using buttons, listeners and text
fields.
Background
Interactivity is what user wants in every application. To add interactivity in a program, Java
provides us a very easy way. Javax.swing.JButton calss provides us a way to add buttons
and events happens after button click. Similarly with the help of javax.swing.JTextfield allow
us to add text fields to JFrame.
Adding text fields
You can create a textfield using JTextfield() method. This class has many constructors like,
JTextField(): It constructs a new text field

JTextField(string text): Constructs a text field with the specified  text.

JTextField(string text, int column): It creats a new text field with the specified text and
number of columns.

Following program shows example of adding text fields to JFrame.

1. package javatutorial.net;
2. import java.awt.FlowLayout;
3. import javax.swing.JFrame;
4. import javax.swing.JTextField;
5.
6.
7. public class Example {
8.
9. static JTextField textfield1, textfield2, textfield3;
10.
11. public static void main(String[] args) {
12.
13. JFrame f = new JFrame("Text Field Examples");
14. f.getContentPane().setLayout(new FlowLayout());
15. textfield1 = new JTextField("Text field 1",10);
16. textfield2 = new JTextField("Text field 2",10);
17. textfield3 = new JTextField("Text field 3",10);
18. f.getContentPane().add(textfield1);
19. f.getContentPane().add(textfield2);
20. f.getContentPane().add(textfield3);
21.
22. f.pack();
23. f.setVisible(true);
24. }
25. }
Output:

TextField example
You can customize by using different mehods provided by the JTextfield.

JTextField.setfont(Font f); It sets the font of text

JTextField.setHorizontalAlignment(int alignment); It sets the horizontal alignment of the text.

JTextFieldsetScrollOffset(int scrolloffset);  It sets the scroll offset in pixels.

Adding buttons and applying action listener


Similarly you can add buttons to your JFrame. JButton provides us an easy way to add
buttons and action listeners. It has many constructors like

JButton(); creates a button with no text and no icon.

JButton(String text): creates a button with specified text.

JButton(Icon icon); creates a button with specified icon.

JButton(String text, Icon icon); creates a button with specified text and icon.

Here is a simple example of JButton with image icon.

1. package javatutorial.net;
2. import javax.swing.ImageIcon;
3. import javax.swing.JButton;
4. import javax.swing.JFrame;
5.
6. public class SimpleJButton {
7.
8. SimpleJButton(){
9. JFrame f=new JFrame("Button Example");
10. JButton b=new JButton("Play", new ImageIcon("play.png"));
11. b.setBounds(100,100,140, 40);
12. f.add(b);
13. f.setSize(300,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. }
18. public static void main(String[] args) {
19. new SimpleJButton();
20. }
21. }
Here is the output of this code

Button with icon


You can customize by using different mehods provided by the JTextfield.

JTextField.setfont(Font f); It sets the font of text

JTextField.setHorizontalAlignment(int alignment); It sets the horizontal alignment of the text.

JTextFieldsetScrollOffset(int scrolloffset);  It sets the scroll offset in pixels.


Adding buttons and applying action listener
Similarly you can add buttons to your JFrame. JButton provides us an easy way to add
buttons and action listeners. It has many constructors like

JButton(); creates a button with no text and no icon.

JButton(String text): creates a button with specified text.

JButton(Icon icon); creates a button with specified icon.

JButton(String text, Icon icon); creates a button with specified text and icon.

Here is a simple example of JButton with image icon.

1. package javatutorial.net;
2. import javax.swing.ImageIcon;
3. import javax.swing.JButton;
4. import javax.swing.JFrame;
5.
6. public class SimpleJButton {
7.
8. SimpleJButton(){
9. JFrame f=new JFrame("Button Example");
10. JButton b=new JButton("Play", new ImageIcon("play.png"));
11. b.setBounds(100,100,140, 40);
12. f.add(b);
13. f.setSize(300,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
17. }
18. public static void main(String[] args) {
19. new SimpleJButton();
20. }
21. }
Here is the output of this code
Button with icon

Adding action listeners


Adding action listeners on a JButton is very easy a simple. JButton class provides a method
JButton.addActionListener() which implements an override method actionPerformed(). Here
in the following example I wrote a simple program which says user to enter name, when
user clicks on submit button, a message “Name has been submitted.” Shows. Here is the
code.

1. package javatutorial.net;
2. import java.awt.event.ActionEvent;
3. import java.awt.event.ActionListener;
4.
5. import javax.swing.JButton;
6. import javax.swing.JFrame;
7. import javax.swing.JLabel;
8. import javax.swing.JTextField;
9.
10. public class SimpleJButton {
11.
12. SimpleJButton(){
13. JFrame f=new JFrame("Button Example");
14. //submit button
15. JButton b=new JButton("Submit");
16. b.setBounds(100,100,140, 40);
17. //enter name label
18. JLabel label = new JLabel();
19. label.setText("Enter Name :");
20. label.setBounds(10, 10, 100, 100);
21. //empty label which will show event after button clicked
22. JLabel label1 = new JLabel();
23. label1.setBounds(10, 110, 200, 100);
24. //textfield to enter name
25. JTextField textfield= new JTextField();
26. textfield.setBounds(110, 50, 130, 30);
27. //add to frame
28. f.add(label1);
29. f.add(textfield);
30. f.add(label);
31. f.add(b);
32. f.setSize(300,300);
33. f.setLayout(null);
34. f.setVisible(true);
35. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
36.
37. //action listener
38. b.addActionListener(new ActionListener() {
39.
40. @Override
41. public void actionPerformed(ActionEvent arg0) {
42. label1.setText("Name has been submitted.");
43. }
44. });
45. }
46.
47.
48. public static void main(String[] args) {
49. new SimpleJButton();
50. }
51. }
Here is the output of this code

Action Listener
Display text and graphics in Java on JFrame
This tutorial explains how to display text and graphics on JFrmae for example, lines, circle
and rectangle.
Background
Java provides us an easy way to draw text and graphics using GUI. Graphics class in AWT
package allow us to draw primitive geometric types like line and circle. Other than this it can
also display text.  This tutorial will explain various functions of Graphics class used to draw
shapes and text.

Draw lines
Graphics class provides a method Graphics.drawline(int x1, int y1, int x2, int y2) to draw a
line on the screen. While x1 is the x-coordinate of first point of line and y1 is y-coordinate of
the first point of line. Similarly x2 and y2 are the coordinates of second point of line.

Here is the program which displays a line.

1. package javatutorial.net;
2. import java.awt.Graphics;
3. import javax.swing.JFrame;
4. import javax.swing.JPanel;
5.
6. public class JFrmaeGraphics extends JPanel{
7.
8. public void paint(Graphics g){
9.
10. g.drawLine(10, 10, 200, 300);
11. }
12.
13. public static void main(String[] args){
14. JFrame frame= new JFrame("Welecome to JavaTutorial.net");
15. frame.getContentPane().add(new JFrmaeGraphics());
16. frame.setSize(600, 400);
17. frame.setVisible(true);
18. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
19. frame.setResizable(false);
20. }
21. }
Here is the output of this code
line example

Draw circles
You can draw circle and oval with the help of method Graphics.drawOval(int x, int y, int
width, int height). This function serves both purposes. X, and y are the position, the starting
point on the screen and width and height are the parameters to set width and height of oval
or circle. For circle set same width and height.

Here the program shows code to draw circle on the screen.

1. package javatutorial.net;
2. import java.awt.Graphics;
3. import javax.swing.JFrame;
4. import javax.swing.JPanel;
5.
6. public class JFrmaeGraphics extends JPanel{
7.
8. public void paint(Graphics g){
9. g.drawOval(100, 100, 100, 100);
10. }
11.
12. public static void main(String[] args){
13. JFrame frame= new JFrame("JavaTutorial.net");
14. frame.getContentPane().add(new JFrmaeGraphics());
15. frame.setSize(300, 300);
16. frame.setVisible(true);
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18. frame.setResizable(false);
19. }
20. }
Here is the output of this code

circle example

Draw rectangles
Graphics class provides a method Graphics.drawRect(int x, int y, int width, int height) to
draw a rectangle or a square. First two parameters shows starting point and last two
parameters shows width and height of rectangle or square. For square width and height
should be same.

Here is the code to draw a rectangle

1. package javatutorial.net;
2. import java.awt.Graphics;
3. import javax.swing.JFrame;
4. import javax.swing.JPanel;
5.
6. public class JFrmaeGraphics extends JPanel{
7.
8. public void paint(Graphics g){
9. g.drawRect(10, 10, 100, 100);
10. }
11.
12. public static void main(String[] args){
13. JFrame frame= new JFrame("JavaTutorial.net");
14. frame.getContentPane().add(new JFrmaeGraphics());
15. frame.setSize(300, 300);
16. frame.setVisible(true);
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18. frame.setResizable(false);
19. }
20. }
Here is the output of this code

rectangle example

Draw polygons
Drawing a polygon is very easy  Graphics class provides a method as
Graphics.drawPolygon(int [], int [], int points). First parameter is an array containing x values
of all point of polygon, second is also an array containing y values of all points of polygon,
while the third parameter shows number of points.

1. package javatutorial.net;
2. import java.awt.Graphics;
3. import javax.swing.JFrame;
4. import javax.swing.JPanel;
5.
6. public class JFrmaeGraphics extends JPanel{
7.
8. public void paint(Graphics g){
9. int xValues[] = {25, 145, 25, 145, 25};
10. int yValues[] = {25, 25, 145, 145, 25};
11. int points = 5;
12. g.drawPolygon(xValues, yValues, points);
13. }
14.
15. public static void main(String[] args){
16. JFrame frame= new JFrame("JavaTutorial.net");
17. frame.getContentPane().add(new JFrmaeGraphics());
18. frame.setSize(300, 300);
19. frame.setVisible(true);
20. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
21. frame.setResizable(false);
22. }
23. }
Here is the output of this code

polygon example

Draw text
To draw text on the screen, you can use Graphics.drawText(string text, int x, int y) method.
First parameter is the string that you want to display and last two parameters are  the value
of point, where this text will start.

Here is the example code

1. package javatutorial.net;
2. import java.awt.Graphics;
3. import javax.swing.JFrame;
4. import javax.swing.JPanel;
5.
6. public class JFrmaeGraphics extends JPanel{
7.
8. public void paint(Graphics g){
9. g.drawString("Hello to JavaTutorial.net", 10, 10);
10. }
11.
12. public static void main(String[] args){
13. JFrame frame= new JFrame("JavaTutorial.net");
14. frame.getContentPane().add(new JFrmaeGraphics());
15. frame.setSize(300, 300);
16. frame.setVisible(true);
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18. frame.setResizable(false);
19. }
20. }
Here is the output of this code

Text example

Draw an Image
Graphics class provides Graphics.drawImage(Image, int x, int y, ImageOberver observer)
method to draw an image. While Image is the class, you can use getDafaultKit() method to 
get the address of image. Place your image in your project’s folder.

Here is the example code

1. package javatutorial.net;
2. import java.awt.Graphics;
3. import java.awt.Image;
4. import java.awt.Toolkit;
5.
6. import javax.swing.JFrame;
7. import javax.swing.JPanel;
8.
9. public class JFrmaeGraphics extends JPanel{
10.
11. public void paint(Graphics g){
12. Image image = Toolkit.getDefaultToolkit().getImage("example.jpg");
13. g.drawImage(image, 10, 10, this);
14. }
15.
16. public static void main(String[] args){
17. JFrame frame= new JFrame("JavaTutorial.net");
18. frame.getContentPane().add(new JFrmaeGraphics());
19. frame.setSize(300, 300);
20. frame.setVisible(true);
21. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
22. frame.setResizable(false);
23. }
24. }
Here is the output of this code

Image example

You might also like