Java Notes
Java Notes
Java Exceptions
When executing Java code, different errors can occur: coding errors made by the
programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The technical
term for this is: Java will throw an exception (throw an error).
The try statement allows you to define a block of code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of code to be executed, if an error occurs in
the try block.
Syntax
try {
catch(Exception e) {
System.out.println(myNumbers[10]); // error!
If an error occurs, we can use try...catch to catch the error and execute some code to handle
it: Example
public class Main {
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
The finally statement lets you execute code, after try...catch, regardless of the
result: Example
try {
System.out.println(myNumbers[10]);
} catch (Exception e) {
} finally {
System.out.println("The 'try catch' is finished.");
The throw statement is used together with an exception type. There are many exception
types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc:
Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
else {
}
The output will be:
Example
checkAge(20);
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the
compiler checks them during compilation to see whether the programmer has handled them or
not. If these exceptions are not handled/declared in the program, you will get compilation
error. For example, SQLException, IOException, ClassNotFoundException etc.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not
checked at compile-time so compiler does not check whether the programmer has handled
them or not but it’s the responsibility of the programmer to handle these exceptions and
provide a safe exit. For example, ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.Java defines several types of exceptions that relate to
its various class libraries. Java also allows users to define their own exceptions.
Built-in Exceptions
Built-in exceptions are the exceptions which are available in Java libraries. These
exceptions are suitable to explain certain error situations. Below is the list of important
built-in exceptions in Java.
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index
is either negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting, sleeping, or doing some processing, and it is
interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric
format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative or
greater than the size of the string
class ArithmeticException_Demo
{
try {
int a = 30, b = 0;
catch(ArithmeticException e) {
Output:
Can't divide a number by 0
• NullPointer Exception
class NullPointer_Demo
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {
System.out.println("NullPointerException.."); }
Output:
NullPointerException..
• StringIndexOutOfBound Exception
class StringIndexOutOfBound_Demo
try {
System.out.println(c);
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException"); }
Output:
StringIndexOutOfBoundsException
• FileNotFound Exception
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
class File_notFound_Demo {
try {
catch (FileNotFoundException e) {
Output:
File does not exist
• NumberFormat Exception
class NumberFormat_Demo
try {
} catch(NumberFormatException e) {
Output:
Number format exception
ArrayIndexOutOfBounds Exception
class ArrayIndexOutOfBound_Demo
try{
// size 5
catch(ArrayIndexOutOfBoundsException e){
Output:
Array Index is Out Of Bounds
User-Defined Exceptions
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In
such cases, user can also create exceptions which are called ‘user-defined Exceptions’.
Following steps are followed for the creation of user-defined Exception.
• The user should create an exception class as a subclass of Exception class. Since all the
exceptions are subclasses of Exception class, the user should also make his class a
subclass of it. This is done as:
class MyException extends Exception
• We
can write a default constructor in his own exception class.
MyException(){}
• Wecan also create a parameterized constructor with a string as a parameter. We
can use this to store exception details. We can call super class(Exception)
constructor from this and send the string there.
MyException(String str)
{
super(str);
}
• To
raise exception of user-defined type, we need to create an object to his exception
class and throw it using throw clause, as:
MyException me = new MyException(“Exception details”);
throw me;
• The following program illustrates how to create own exception class MyException. •
Details of account numbers, customer names, and balance amounts are taken in the
form of three arrays.
• In main() method, the details are displayed using a for-loop. At this time, check is done if in
any account the balance amount is less than the minimum balance amount to be apt in the
account.
• If it is so, then MyException is raised and a message is displayed “Balance amount is
less”
default constructor
MyException() { }
// parameterized constructor
// write main()
try {
bal[i]);
MyException me =
} //end of try
catch (MyException e) {
e.printStackTrace();
RunTime Error
MyException: Balance is less than 1000
at MyException.main(fileProperty.java:36)
Output:
ACCNO CUSTOMER BALANCE
1001 Nish 10000.0
1002 Shubh 12000.0
1003 Sush 5600.0
1004 Abhi 999.0
Java Streams
Java provides I/O Streams to read and write data where, a Stream represents an input source
or an output destination which could be a file, i/o devise, other program etc.
In general, a Stream will be an input stream or, an output stream.
• ByteStreams − These handle data in bytes (8 bits) i.e., the byte stream
classes read/write data of 8 bits. Using these you can store
characters, videos, audios, images etc.
• Character
Streams − These handle data in 16 bit Unicode. Using these
you can read and write text data only.
Standard Streams
In addition to above mentioned classes Java provides 3 standard streams representing the
input and, output devices.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy
an input file into an output file –
Some important Byte stream classes.
Example
import java.io.*;
FileInputStream in = null;
try {
in = new FileInputStream("input.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
}
}
As a next step, compile the above program and execute it, which will
result in creating an output.txt file with the same content as we have in
input.txt. So let's put the above code in CopyFile.java file and do the
following −
$javac CopyFile.java
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas Java
Character streams are used to perform input and output for 16-bit Unicode. Though there are
many classes related to character streams but the most frequently used classes are,
FileReader and FileWriter. Though internally FileReader uses FileInputStream and
FileWriter uses FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
We can re-write the above example, which makes the use of these two
classes to copy an input file (having Unicode characters) into an output
file −
Example
import java.io.*;
FileReader in = null;
try {
in = new FileReader("input.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}finally {
if (in != null) {
in.close();
if (out != null) {
out.close();
As a next step, compile the above program and execute it, which will
result in creating an output.txt file with the same content as we have in
input.txt. So let's put the above code in CopyFile.java file and do the
following −
$javac CopyFile.java
$java CopyFile
import java.io.*;
class MyInput
{
{ String text;
InputStreamReader isr = new InputStreamReader(System.in);
System.out.println(text);
class ReadTest
try
String str;
while ((str=br.readLine())!=null)
System.out.println(str);
br.close();
fl.close();
}
catch(IOException e) {
e.printStackTrace();
class WriteTest
try
fw.write(str);
fw.close();
fl.close();
catch (IOException e)
{ e.printStackTrace(); }
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
throws IOException
new InputStreamReader(System.in));
// Reading data using readLine
System.out.println(name);
Input:
Geek
Output:
Geek
Note:
This is probably the most preferred method to take input. The main purpose of the Scanner
class is to parse primitive types and strings using regular expressions, however, it is also can
be used to read input from the user in the command line.
• Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized
input.
• Regular expressions can be used to find tokens.
class GetInputFromUser {
in.nextLine();
a = in.nextInt();
float b = in.nextFloat();
in.close();
Input:
GeeksforGeeks
12
3.4
Output:
You entered string GeeksforGeeks
You entered integer 12
You entered float 3.4
3. Using Console Class
It has been becoming a preferred way for reading user’s input from the command line. In
addition, it can be used for reading password-like input without echoing the characters
entered by the user; the format string syntax can also be used (like System.out.printf()).
Advantages:
Input:
GeeksforGeeks
Output:
Most used user input for competitive coding. The command-line arguments are stored in the
String format. The parseInt method of the Integer class converts string argument into Integer.
Similarly, for float and others during execution. The usage of args[] comes into existence in
this input form. The passing of information takes place during the program run. The
command line is given to args[]. These programs have to be run on cmd.
class Hello {
// greater than 0
if (args.length > 0) {
System.out.println(
else
javac GFG1.java
java Main Hello World
Output:
Interfaces
An interface is a completely "abstract class" that is used to group related methods with
empty bodies:
Example
// interface
interface Animal {
To access the interface methods, the interface must be "implemented" (kinda like inherited)
by another class with the implements keyword (instead of extends). The body of the interface
method is provided by the "implement" class:
Example
// Interface
interface Animal {
}
public void sleep() {
System.out.println("Zzz");
class Main {
myPig.animalSound();
myPig.sleep();
Output:
Notes on Interfaces:
• Likeabstract classes, interfaces cannot be used to create objects (in the example
above, it is not possible to create an "Animal" object in the MyMainClass) • Interface
methods do not have a body - the body is provided by the "implement" class • On
implementation of an interface, you must override all of its methods • Interface methods
are by default abstract and public
• Interface attributes are by default public, static and final
1) To achieve security - hide certain details and only show the important details of an object
(interface).
2) Java does not support "multiple inheritance" (a class can only inherit from one superclass).
However, it can be achieved with interfaces, because the class can implement multiple
interfaces. Note: To implement multiple interfaces, separate them with a comma (see
example below).
Multiple Interfaces
comma: Example
interface FirstInterface {
interface SecondInterface {
System.out.println("Some text..");
class Main {
myObj.myMethod();
myObj.myOtherMethod();
}
output
Some text...
Some other text...
There are mainly three reasons to use interface. They are given below.
A class extends another class, an interface extends another interface, but a class implements
an interface.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }
Output:
Hello
Java Interface Example: Bank
Let's see another example of java interface which provides the implementation of
Bank interface.
File: TestInterface2.java
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10.class TestInterface2{
11.public static void main(String[] args){
12.Bank b=new SBI();
13.System.out.println("ROI: "+b.rateOfInterest());
14.}}
Output::
ROI: 9.15
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.public static void main(String args[]){
11.A7 obj = new A7();
12.obj.print();
13.obj.show();
14. }
15.}
Test it Now
Output:Hello
Welcome
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at the same
time.
Threads can be used to perform complicated tasks in the background without interrupting the
main program.
Creating a Thread
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
Implement Syntax
}
Running Threads
If the class extends the Thread class, the thread can be run by creating an instance of the class
and call its start() method:
Extend Example
thread.start();
}
public void run() {
output
This code is outside of the thread
This code is running in a thread
Try it Yourself »
If the class implements the Runnable interface, the thread can be run by passing an instance
of the class to a Thread object's constructor and then calling the thread's start() method:
Implement Example
output
This code is outside of the thread
This code is running in a thread
Try it Yourself »
Differences between "extending" and "implementing" Threads
The major difference is that when a class extends the Thread class, you cannot extend any
other class, but by implementing the Runnable interface, it is possible to extend from another
class as well, like: class MyClass extends OtherClass implements Runnable.
Concurrency Problems
Because threads run at the same time as other parts of the program, there is no way to know in
which order the code will run. When the threads and main program are reading and writing
the same variables, the values are unpredictable. The problems that result from this are called
concurrency problems.
Example
thread.start();
System.out.println(amount);
amount++;
System.out.println(amount);
amount++;
Output
0
2
To avoid concurrency problems, it is best to share as few attributes between
threads as possible. If attributes need to be shared, one possible solution is
to use the isAlive() method of the thread to check whether the thread
has finished running before using any attributes that the thread can change.
Example
public class Main extends Thread {
thread.start();
// Wait for the thread to finish
while(thread.isAlive()) {
System.out.println("Waiting...");
amount++;
}
public void run() {
amount++;
Output
Waiting. . .
Main: 1
Main: 2
Multithreading in Java
Multithreading in Java is a process of executing multiple threads simultaneously.
However, we use multithreading than multiprocessing because threads use a shared memory
area. They don't allocate separate memory area so saves memory, and context-switching
between the threads takes less time than process.
try {
System.out.println(
running");
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught"); }
// Main Class
MultithreadingDemo object
= new MultithreadingDemo();
object.start(); }
}
}
Output
Thread 15 is
running Thread 14
is running Thread
16 is running
Thread 12 is
running Thread 11
is running Thread
13 is running
Thread 18 is
running Thread 17
is running
UNIT 5
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Java JButton
The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.
Output:
Java JTextField
The object of a JTextField class is a text component that allows the editing of a
single line text. It inherits JTextComponent class.
Output:
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits JTextComponent class
Output:
Java JCheckBox Example: Food Order
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class CheckBoxExample extends JFrame implements
ActionListener{ 4. JLabel l;
5. JCheckBox cb1,cb2,cb3;
6. JButton b;
7. CheckBoxExample(){
8. l=new JLabel("Food Ordering System");
9. l.setBounds(50,50,300,20);
10. cb1=new JCheckBox("Pizza @ 100");
11. cb1.setBounds(100,100,150,20);
12. cb2=new JCheckBox("Burger @ 30");
13. cb2.setBounds(100,150,150,20);
14. cb3=new JCheckBox("Tea @ 10");
15. cb3.setBounds(100,200,150,20);
16. b=new JButton("Order");
17. b.setBounds(100,250,80,30);
18. b.addActionListener(this);
19. add(l);add(cb1);add(cb2);add(cb3);add(b);
20. setSize(400,400);
21. setLayout(null);
22. setVisible(true);
23. setDefaultCloseOperation(EXIT_ON_CLOSE);
24. }
25. public void actionPerformed(ActionEvent e){
26. float amount=0;
27. String msg="";
28. if(cb1.isSelected()){
29. amount+=100;
30. msg="Pizza: 100\n";
31. }
32. if(cb2.isSelected()){
33. amount+=30;
34. msg+="Burger: 30\n";
35. }
36. if(cb3.isSelected()){
37. amount+=10;
38. msg+="Tea: 10\n";
39. }
40. msg+="-----------------\n";
41. JOptionPane.showMessageDialog(this,msg+"Total: "+amount); 42. }
43. public static void main(String[] args) {
44. new CheckBoxExample();
45. }
46.}
Output:
Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one
option from multiple options. It is widely used in exam systems or quiz.
1. import javax.swing.*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new JRadioButton("B) Female");
8. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10.ButtonGroup bg=new ButtonGroup();
11.bg.add(r1);bg.add(r2);
12.f.add(r1);f.add(r2);
13.f.setSize(300,300);
14.f.setLayout(null);
15.f.setVisible(true);
16.}
17.public static void main(String[] args) {
18. new RadioButtonExample();
19.}
20.}
Output:
Java JComboBox
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 JComponent class.
Output:
Java JList
The object of JList class represents a list of text items. The list of text items can be
set up so that the user can choose either one item or multiple items. It inherits
JComponent class.
Java JList Example
1. import javax.swing.*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>(); 7.
l1.addElement("Item1");
8. l1.addElement("Item2");
9. l1.addElement("Item3");
10. l1.addElement("Item4");
11. JList<String> list = new JList<>(l1);
12. list.setBounds(100,100, 75,75);
13. f.add(list);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18.public static void main(String args[])
19. {
20. new ListExample();
21. }}
Output:
Java JScrollBar
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an
implementation of a scrollbar. It inherits JComponent class.
1. import javax.swing.*;
2. class ScrollBarExample
3. {
4. ScrollBarExample(){
5. JFrame f= new JFrame("Scrollbar Example");
6. JScrollBar s=new JScrollBar();
7. s.setBounds(100,100, 50,100);
8. f.add(s);
9. f.setSize(400,400);
10.f.setLayout(null);
11.f.setVisible(true);
12.}
13.public static void main(String args[])
14.{
15.new ScrollBarExample();
16.}}
Output:
Java JMenuBar, JMenu and JMenuItem
The JMenuBar class is used to display menubar on the window or frame. It may have
several menus.
The object of JMenu class is a pull down menu component which is displayed from
the menu bar. It inherits the JMenuItem class.
The object of JMenuItem class adds a simple labeled menu item. The items used in a
menu must belong to the JMenuItem or any of its subclass.
Output:
Output:
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message
dialog box, confirm dialog box and input dialog box. These dialog boxes are used to
display information or get input from the user. The JOptionPane class inherits
JComponent class.
Output:
Output:
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
Drawback of Applet
1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class
provides 1 life cycle methods for an applet.
java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life
cycle methods of applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is
maximized. It is used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is
stop or browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
1. By html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome",150,150);
}
}
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{
public void paint(Graphics g){
g.drawString("welcome to applet",150,150);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
c:\>javac First.java
c:\>appletviewer First.java
A Simple Applet
import java.awt.*;
import java.applet.*;
}
Example of an Applet Skeleton
import java.awt.*;
import java.applet.*;
//initialization
//suspend execution
}
Example of an Applet
import java.applet.*;
import java.awt.*;
height = getSize().height;
width = getSize().width;
setName("MyApplet");
3); }
}
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.
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
o MenuItem
o TextArea
o Checkbox
o List
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
String msg="";
addKeyListener(this);
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
showStatus("KeyRealesed");
msg = msg+k.getKeyChar();
repaint();
HTML code:
</applet>
Java MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in java.awt.event package. It has five methods.
Output:
Java MouseListener Example 2
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample2 extends Frame implements MouseListener{
4. MouseListenerExample2(){
5. addMouseListener(this);
6.
7. setSize(300,300);
8. setLayout(null);
9. setVisible(true);
10. }
11. public void mouseClicked(MouseEvent e) {
12. Graphics g=getGraphics();
13. g.setColor(Color.BLUE);
14. g.fillOval(e.getX(),e.getY(),30,30);
15. }
16. public void mouseEntered(MouseEvent e) {}
17. public void mouseExited(MouseEvent e) {}
18. public void mousePressed(MouseEvent e) {}
19. public void mouseReleased(MouseEvent e) {}
20.
21.public static void main(String[] args) {
22. new MouseListenerExample2(); }}
Output:
Output:
Java LayoutManagers
The LayoutManagers are used to arrange components in a particular manner. LayoutManager
is an interface that is implemented by all the classes of layout managers. There are following
classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south,
east, west and center. Each region (area) may contain one component only. It is the
default layout of frame or window. The BorderLayout provides five constants for
each region:
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new JButton("CENTER");;
14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.CENTER);
20.
21. f.setSize(300,300);
22. f.setVisible(true);
23.}
24.public static void main(String[] args) {
25. new Border();
26.}
27.}
Java GridLayout
The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyGridLayout{
5. JFrame f;
6. MyGridLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14. JButton b6=new JButton("6");
15. JButton b7=new JButton("7");
16. JButton b8=new JButton("8");
17. JButton b9=new JButton("9");
18.
19. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5); 20.
f.add(b6);f.add(b7);f.add(b8);f.add(b9); 21.
22. f.setLayout(new GridLayout(3,3));
23. //setting grid layout of 3 rows and 3 columns
24.
25. f.setSize(300,300);
26. f.setVisible(true);
27.}
28.public static void main(String[] args)
{ 29. new MyGridLayout();
30.}
31.}
Java FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It
is the default layout of applet or panel.
1. import java.awt.*;
2. import javax.swing.*;
3.
4. public class MyFlowLayout{
5. JFrame f;
6. MyFlowLayout(){
7. f=new JFrame();
8.
9. JButton b1=new JButton("1");
10. JButton b2=new JButton("2");
11. JButton b3=new JButton("3");
12. JButton b4=new JButton("4");
13. JButton b5=new JButton("5");
14.
15. f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
16.
17. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
18. //setting flow layout of right alignment
19.
20. f.setSize(300,300);
21. f.setVisible(true);
22.}
23.public static void main(String[] args) {
24. new MyFlowLayout();
25.}
26.}
Java GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or
along their baseline.
The components may not be of same size. Each GridBagLayout object maintains a
dynamic, rectangular grid of cells. Each component occupies one or more cells known
as its display area. Each component associates an instance of GridBagConstraints.
With the help of constraints object we arrange component's display area on the grid.
The GridBagLayout manages each component's minimum and preferred sizes in order
to determine component's size.
Example
1. import java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import java.awt.GridBagLayout;
4.
5. import javax.swing.*;
6. public class GridBagLayoutExample extends JFrame{
7. public static void main(String[] args) {
8. GridBagLayoutExample a = new GridBagLayoutExample(); 9. }
10. public GridBagLayoutExample() {
11. GridBagLayoutgrid = new GridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints(); 13.
setLayout(grid);
14. setTitle("GridBag Layout Example");
15. GridBagLayout layout = new GridBagLayout(); 16.
this.setLayout(layout);
17. gbc.fill = GridBagConstraints.HORIZONTAL;
18. gbc.gridx = 0;
19. gbc.gridy = 0;
20. this.add(new Button("Button One"), gbc);
21. gbc.gridx = 1;
22. gbc.gridy = 0;
23. this.add(new Button("Button two"), gbc);
24. gbc.fill = GridBagConstraints.HORIZONTAL;
25. gbc.ipady = 20;
26. gbc.gridx = 0;
27. gbc.gridy = 1;
28. this.add(new Button("Button Three"), gbc);
29. gbc.gridx = 1;
30. gbc.gridy = 1;
31. this.add(new Button("Button Four"), gbc);
32. gbc.gridx = 0;
33. gbc.gridy = 2;
34. gbc.fill = GridBagConstraints.HORIZONTAL;
35. gbc.gridwidth = 2;
36. this.add(new Button("Button Five"), gbc);
37. setSize(300, 300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_ON_CLOSE); 41.
42. }
43.
44.}
Output: