java unit-5

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Java AWT

Java AWT (Abstract Window Toolkit) is an API to develop Graphical User Interface (GUI)
or windows-based applications in Java. Java AWT is part of the Java Foundation Classes
(JFC) that provides a way to build platform-independent graphical applications.

Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavy weight i.e. its components are using the
resources of underlying operating system (OS).

The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

AWT is platform independent even after the AWT components are platform dependent
because of the points mentioned below:
1. JVM (Java Virtual Machine):
As Java Virtual Machine is platform dependent
2. Abstract APIs:
AWT provides an abstract layer for GUI. Java applications interact with AWT through
Abstract API which are platform independent. Abstract API allows Java to isolate platform-
specific details, making code portable across different systems.
3. Platform-Independent Libraries:
The Libraries of AWT are written in Java which they are totally platform-independent.
Because of this, it ensures that AWT functionality remains consistent across different
environments.
Java AWT Hierarchy

 Components: AWT provides various components such as buttons, labels, text fields,
checkboxes, etc used for creating GUI elements for Java Applications.
 Containers: AWT provides containers like panels, frames, and dialogues to organize
and group components in the Application.
Types of containers:

There are four types of containers in Java AWT:

1. Window
2. Panel
3. Frame
4. Dialog

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. We need to create an instance of Window class to
create this container.

Panel
The Panel is the container that doesn't contain title bar, border or menu bar. It is generic
container for holding the components. It can have other components like button, text field etc.
An instance of Panel class creates a container, in which we can add components.

Frame
The Frame is the container that contain title bar and border and can have menu bars. It can
have other components like button, text field, scrollbar etc. Frame is most widely used
container while developing an AWT application.

Dialog: A dialog box is a temporary window an application creates to retrieve user input.
Java Swing
Java Swing was introduced as part of the Java Foundation Classes (JFC) in the late 1990s,
aiming to address the limitations of the earlier Abstract Window Toolkit (AWT).

Swing provides a comprehensive set of components for building GUIs, including buttons,
text fields, panels, and more. These components are highly customizable, allowing
developers to create visually appealing and user-friendly interfaces.
Key Features of Java Swing
Platform Independence: One of the primary advantages of Swing is its platform
independence. Applications developed using Swing can run on any platform that supports
Java, without requiring modifications.

Rich Set of Components: Swing offers a wide range of components that can be used to
create complex GUIs. Developers can choose from basic components like buttons and labels
to advanced components such as tables, trees, and scroll panes.

Customizability: Swing components are highly customizable, allowing developers to control


various aspects of their appearance and behavior. Properties such as size, color, font, and
layout can be easily adjusted to meet specific design requirements.

Event Handling: Swing provides a robust event handling mechanism that allows developers
to respond to user interactions, such as button clicks and mouse movements. This enables the
creation of interactive and responsive applications.
Layout Managers: Swing includes a set of layout managers that facilitate the arrangement of
components within a container. Layout managers automatically adjust the position and size of
components based on the container's size, ensuring consistent behavior across different
screen resolutions and devices.

Difference between Java Swing and Java AWT


There are certain points from which Java Swing is different than Java AWT as mentioned
below:
Java AWT Java Swing

Java AWT is an API to develop GUI Swing is a part of Java Foundation Classes
applications in Java. and is used to create various applications.

The components of Java Swing are


Components of AWT are heavy weighted.
lightweight.

Components are platform dependent. Components are platform independent.

Execution Time is more than Swing. Execution Time is less than AWT.

AWT components require java.awt Swing components requires javax.swing


package. package.

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.
Java JFrame

The javax.swing.JFrame class is a type of container which inherits the java.awt.Frame class.
JFrame works like the main window where components like labels, buttons, textfields are
added to create a GUI.

Methods of Java JFrame


Methods Description

setTitle(String title) Sets the title of the JFrame.

setSize(int width, int height) Sets the size of the JFrame.

Sets the default close operation for the


JFrame. Common options include
setDefaultCloseOperation(int
JFrame.EXIT_ON_CLOSE,
operation)
JFrame.HIDE_ON_CLOSE, and
JFrame.DO_NOTHING_ON_CLOSE.
Methods Description

Sets the visibility of the JFrame. Pass true to


setVisible(boolean b)
make it visible and false to hide it.

Sets the layout manager for the JFrame,


setLayout(LayoutManager manager) which controls how components are arranged
within the frame.

add(Component comp) Adds a Swing component to the JFrame.

remove(Component comp) Removes a component from the JFrame.

Forces the layout manager to recalculate the


validate()
layout of components within the JFrame.

Controls whether the user can resize the


setResizable(boolean resizable)
JFrame.

setIconImage(Image image) Sets the icon (image) for the JFrame window.

1. import java.awt.FlowLayout;
2. import javax.swing.JButton;
3. import javax.swing.JFrame;
4. import javax.swing.JLabel;
5. import javax.swing.JPanel;
6. public class JFrameExample {
7. public static void main(String s[]) {
8. JFrame frame = new JFrame("JFrame Example");
9. JPanel panel = new JPanel();
10. panel.setLayout(new FlowLayout());
11. JLabel label = new JLabel("JFrame By Example");
12. JButton button = new JButton();
13. button.setText("Button");
14. panel.add(label);
15. panel.add(button);
16. frame.add(panel);
17. frame.setSize(200, 300);
18. frame.setLocationRelativeTo(null);
19. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. frame.setVisible(true);
21. }
22. }
Output
JApplet :

As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing. The
JApplet class extends the Applet class.

Sample applet program

myapplet.html
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Example of EventHandling in JApplet:


1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void init(){
8.
9. tf=new JTextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new JButton("Click");
13. b.setBounds(80,150,70,40);
14.
15. add(b);add(tf);
16. b.addActionListener(this);
17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welcome");
23. }
24. }
25.

JDialog

The JDialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Dialog class.Unlike JFrame, it doesn't have
maximize and minimize buttons.

JDialog class declaration


Let's see the declaration for javax.swing.JDialog class.

public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneC


ontainer
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class DialogExample {
5. private static JDialog d;
6. DialogExample() {
7. JFrame f= new JFrame();
8. d = new JDialog(f , "Dialog Example", true);
9. d.setLayout( new FlowLayout() );
10. JButton b = new JButton ("OK");
11. b.addActionListener ( new ActionListener()
12. {
13. public void actionPerformed( ActionEvent e )
14. {
15. DialogExample.d.setVisible(false);
16. }
17. });
18. d.add( new JLabel ("Click button to continue."));
19. d.add(b);
20. d.setSize(300,300);
21. d.setVisible(true);
22. }
23. public static void main(String args[])
24. {
25. new DialogExample();
26. }
27. }
Output:
JPanel

JPanel, a part of the Java Swing package, is a container that can store a group of components.
The main task of JPanel is to organize components, various layouts can be set in JPanel
which provide better organization of components, however, it does not have a title bar.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class solution extends JFrame
{
static JFrame f;
static JButton b, b1, b2;
static JLabel l;
public static void main(String[] args)
{
f = new JFrame("panel");
l = new JLabel("panel label");

b = new JButton("button1");
b1 = new JButton("button2");
b2 = new JButton("button3");
JPanel p = new JPanel();
p.add(b);
p.add(b1);
p.add(b2);
p.add(l);
p.setBackground(Color.red);
f.add(p);
f.setSize(300, 300);
f.show();
}
}

Output:
Types of Layout Manager in Java

In Java, graphical user interfaces (GUIs) play a vital role in creating interactive applications.
To design a visually appealing and organized interface, the choice of layout manager
becomes crucial. Layout managers define how components are arranged within a container,
such as a JFrame or JPanel. Java provides several layout managers to suit various design
needs. In this section, we will delve into the details of the different types of layout managers
available in Java, along with code examples and explanations.

1. FlowLayout
FlowLayout is a simple layout manager that arranges components in a row, left to right,
wrapping to the next line as needed. It is ideal for scenarios where components need to
maintain their natural sizes and maintain a flow-like structure.

FlowLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class FlowLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("FlowLayout Example");
6. frame.setLayout(new FlowLayout());
7. frame.add(new JButton("Button 1"));
8. frame.add(new JButton("Button 2"));
9. frame.add(new JButton("Button 3"));
10. frame.pack();
11. frame.setVisible(true);
12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13. }
14. }
Output:

2. BorderLayout
BorderLayout divides the container into five regions: NORTH, SOUTH, EAST, WEST, and
CENTER. Components can be added to these regions, and they will occupy the available
space accordingly. This layout manager is suitable for creating interfaces with distinct
sections, such as a title bar, content area, and status bar.

BorderLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class BorderLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("BorderLayout Example");
6. frame.setLayout(new BorderLayout());
7. frame.add(new JButton("North"), BorderLayout.NORTH);
8. frame.add(new JButton("South"), BorderLayout.SOUTH);
9. frame.add(new JButton("East"), BorderLayout.EAST);
10. frame.add(new JButton("West"), BorderLayout.WEST);
11. frame.add(new JButton("Center"), BorderLayout.CENTER);
12. frame.pack();
13. frame.setVisible(true);
14. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
15. }
16. }
Output:

3. GridLayout
GridLayout arranges components in a grid with a specified number of rows and columns.
Each cell in the grid can hold a component. This layout manager is ideal for creating a
uniform grid of components, such as a calculator or a game board.

GridLayoutExample.java

1. import javax.swing.*;
2. import java.awt.*;
3. public class GridLayoutExample {
4. public static void main(String[] args) {
5. JFrame frame = new JFrame("GridLayout Example");
6. frame.setLayout(new GridLayout(3, 3));
7. for (int i = 1; i <= 9; i++) {
8. frame.add(new JButton("Button " + i));
9. }
10. frame.pack();
11. frame.setVisible(true);
12. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
13. }
14. }
Output:

You might also like