Event Handling in Java
Event Handling in Java
Types of Events
1. Foreground Events
Foreground events are the events that require user interaction to
generate, i.e., foreground events are generated due to interaction
by the user on components in Graphic User Interface (GUI).
Interactions are nothing but clicking on a button, scrolling the
scroll bar, cursor moments, etc.
2. Background Events
Events that don’t require interactions of users to generate are
known as background events. Examples of these events are
operating system failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what
should happen after an event occur. To handle the events,
Java follows the Delegation Event model.
Delegation Event model
It has Sources and Listeners.
ActionListener actionPerformed()
AdjustmentListener adjustmentValueChanged()
componentResized()
componentShown()
ComponentListener
componentMoved()
componentHidden()
componentAdded()
ContainerListener
componentRemoved()
focusGained()
FocusListener
focusLost()
ItemListener itemStateChanged()
keyTyped()
KeyListener keyPressed()
keyReleased()
mousePressed()
mouseClicked()
MouseListener mouseEntered()
mouseExited()
mouseReleased()
MouseMotionListene mouseMoved()
r mouseDragged()
MouseWheelListener mouseWheelMoved()
TextListener textChanged()
WindowListener windowActivated()
windowDeactivated()
windowOpened()
Listener Interface Methods
windowClosed()
windowClosing()
windowIconified()
windowDeiconified()
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFGTop()
{
// Component Creation
textField = new TextField();
// setBounds method is used to provide
// position and size of the component
textField.setBounds(60, 50, 180, 25);
Button button = new Button("click Here");
button.setBounds(100, 120, 80, 30);
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
Output
After Clicking, the text field value is set to GFG!
Explanation
1. Firstly extend the class with the applet and implement the
respective listener.
2. Create Text-Field and Button components.
3. Registered the button component with respective event.
i.e. ActionEvent by addActionListener().
4. In the end, implement the abstract method.
Event Handling by Other Class
Java
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFG2()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
// set visibility
setVisible(true);
}
Java
GFG2 gfgObj;
Other(GFG1 gfgObj) {
this.gfgObj = gfgObj;
}
import java.awt.*;
import java.awt.event.*;
TextField textField;
GFG3()
{
// Component Creation
textField = new TextField();
// add Components
add(textField);
add(button);
Output
Handling anonymously
MouseListener and MouseMotionListener in
Java
Last Updated : 22 Dec, 2022
MouseListener and MouseMotionListener is an interface in
java.awt.event package . Mouse events
are of two types. MouseListener handles the events when the
mouse is not in motion. While MouseMotionListener
handles the events when mouse is in motion.
There are five types of events that MouseListener can generate.
There are five abstract functions that represent these five
events. The abstract functions are :
Java
// Java program to handle MouseListener events
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mouse extends Frame implements MouseListener {
// default constructor
Mouse()
{
}
// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener");
f.show();
}
// show the point where the user released the mouse click
label1.setText("mouse released at point:"
+ e.getX() + " " + e.getY());
}
// show the point through which the mouse exited the frame
label2.setText("mouse exited through point:"
+ e.getX() + " " + e.getY());
}
Output :
Java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GFG extends Applet implements MouseListener
{
public void init()
{
this.addMouseListener (this);
//first "this" represent source
//(in this case it is applet which
//is current calling object) and
//second "this" represent
//listener(in this case it is GFG)
}
public void mouseClicked(MouseEvent m)
{
int x = m.getX();
int y = m.getY();
String str = "x =" +x+",y = "+y;
showStatus(str);
}
@Override
public void mousePressed(MouseEvent e) {
@Override
public void mouseReleased(MouseEvent e) {
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
}
Output:
Java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GFG extends Applet implements MouseListener
{
private int x,y;
private String str = " ";
public void init()
{
this.addMouseListener (this);
//first "this" represent source
//(in this case it is applet which
// is current calling object) and
// second "this" represent listener
//(in this case it is GFG)
}
public void paint(Graphics g)
{
g.drawString(str,x,y);
}
public void mouseClicked(MouseEvent m)
{
x = m.getX();
y = m.getY();
str = "x =" +x+",y = "+y;
repaint(); // we have made this
//call because repaint() will
//call paint() method for us.
//If we comment out this line,
//then we will see output
//only when focus is on the applet
//i.e on maximising the applet window
//because paint() method is called
//when applet screen gets the focus.
//repaint() is a method of Component
//class and prototype for this method is:
//public void repaint()
Java
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GFG extends Applet implements MouseListener
{
private int x,y;
private String str = " ";
public void init()
{
this.addMouseListener (this);
}
public void paint(Graphics g)
{
g.drawString(str,x,y);
}
public void update(Graphics g)
{
paint(g);
}
public void mouseClicked(MouseEvent m)
{
x = m.getX();
y = m.getY();
str = "x =" +x+",y = "+y;
repaint();
}
public void mouseEntered(MouseEvent m)
{
}
public void mouseExited(MouseEvent m)
{
}
public void mousePressed(MouseEvent m)
{
}
public void mouseReleased(MouseEvent m)
{
}
}
Output
Java
// default constructor
Mouse()
{
}
// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseMotionListener");
f.show();
}
Output :
3. Java program to illustrate MouseListener and
MouseMotionListener events
simultaneously
Java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Mouse extends Frame implements MouseMotionListener,
MouseListener {
// default constructor
Mouse()
{
}
// main class
public static void main(String[] args)
{
// create a frame
JFrame f = new JFrame("MouseListener and
MouseMotionListener");
f.show();
}
// MouseMotionListener events
// MouseListener events
// show the point where the user released the mouse click
label3.setText("mouse released at point:"
+ e.getX() + " " + e.getY());
}
// show the point through which the mouse exited the frame
label4.setText("mouse exited through point:"
+ e.getX() + " " + e.getY());
}
// this function is invoked when the mouse enters the
component
public void mouseEntered(MouseEvent e)
{
output :
MouseListener vs MouseMotionListener
// Constructor
public KeyListenerExample() {
// Set frame properties
setTitle("Typed Text Display");
setSize(400, 200);
setLayout(new FlowLayout());
Output:
Example 2:
Below is the implementation of Java KeyListener:
Java
// Constructor
public KeyListenerExample() {
// Set frame properties
setTitle("Typed Text Display");
setSize(400, 200);
setLayout(new FlowLayout());
import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame jframe = new JFrame("GUI Screen"); //create
JFrame object
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(400,400); //set size of GUI
screen
jframe.setVisible(true);
}
}
STEP 2: Save and compile the code as mentioned above and then run it.
STEP 3: Adding buttons to the above frame. To create a component in Java,
the user is required to create an object of that component’s class. We have
already understood the container class JFrame.
One such component to implement is JButton. This class represents the
clickable buttons. In any application or program, buttons trigger user actions.
Literally, every action begins with a click; like to close an application, the
user would click on the close button.
A swing can also be inserted, which can feature a text, a graphical icon or a
combination of both. A user can use the following constructors:
import javax.swing.*;
class gui{
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(400,400);
jframe.getContentPane().add(firstButton);
jframe.getContentPane().add(secondButton);
jframe.setVisible(true);
}
STEP 6: Save, compile and run the above code.
STEP 7: Unpredicted output = ? It means that the buttons are getting
overlapped.
STEP 8: A user can create chat frames as well. Below is an example of the
same:
import javax.swing.*;
import java.awt.*;
class gui {
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setSize(400, 400);
// create two menubar button FILE and HELP
menuBar.add(fileMenu);
menuBar.add(helpMenu);
fileMenu.add(fileMenu1);
fileMenu.add(fileMenu2);
panel.add(textField);
panel.add(btn_send);
panel.add(btn_reset);
jframe.getContentPane().add(BorderLayout.SOUTH,
panel);
jframe.getContentPane().add(BorderLayout.NORTH,
menuBar);
jframe.getContentPane().add(BorderLayout.CENTER,
textArea);
jframe.setVisible(true);
Conclusion
It can be concluded that creating GUI in Java is a very easy and user-friendly
process as the Java applications provide customization according to the
requirements of the user. To learn more about Java, and to become an
expert in Java development go to NIIT and check out the courses that give
great insight on Java.
Execution Time is more than Swing. Execution Time is less than AWT.
To know more about the topic, refer to Java Swing vs Java AWT.
What is JFC?
JFC stands for Java Foundation Classes. JFC is the set of GUI
components that simplify desktop Applications. Many
programmers think that JFC and Swing are one and the same
thing, but that is not so. JFC contains Swing [A UI component
package] and quite a number of other items:
Cut and paste: Clipboard support.
Accessibility features: Aimed at developing GUIs for users
with disabilities.
The Desktop Colors Features were first introduced in Java
1.1
Java 2D: it has Improved colors, images, and text support.
Features Of Swing Class
Pluggable look and feel.
Uses MVC architecture.
Lightweight Components
Platform Independent
Advanced features such as JTable, JTabbedPane,
JScollPane, etc.
Java is a platform-independent language and runs on any
client machine, the GUI look and feel, owned and
delivered by a platform-specific O/S, simply does not
affect an application’s GUI constructed using Swing
components.
Lightweight Components: Starting with the JDK 1.1, its
AWT-supported lightweight component development. For
a component to qualify as lightweight, it must not depend
on any non-Java [O/s based) system classes. Swing
components have their own view supported by Java’s look
and feel classes.
Pluggable Look and Feel: This feature enable the user
to switch the look and feel of Swing components without
restarting an application. The Swing library supports
components’ look and feels that remain the same across
all platforms wherever the program runs. The Swing
library provides an API that gives real flexibility in
determining the look and feel of the GUI of an application
Highly customizable – Swing controls can be
customized in a very easy way as visual appearance is
independent of internal representation.
Rich controls– Swing provides a rich set of advanced
controls like Tree TabbedPane, slider, colorpicker, and
table controls.
Swing Classes Hierarchy
// Main class
class GFG {
Output:
Example 2: Write a program to create three buttons with caption
OK, SUBMIT, CANCEL.
Java
// Java program to create three buttons
// with caption OK, SUBMIT, CANCEL
import java.awt.*;
class button {
button()
{
Frame f = new Frame();
// Button 1 created
// OK button
Button b1 = new Button("OK");
b1.setBounds(100, 50, 50, 50);
f.add(b1);
// Button 2 created
// Submit button
Button b2 = new Button("SUBMIT");
b2.setBounds(100, 101, 50, 50);
f.add(b2);
// Button 3 created
// Cancel button
Button b3 = new Button("CANCEL");
b3.setBounds(100, 150, 80, 50);
f.add(b3);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}
Output:
Output of Example 2
Example 3: Program to Add Checkbox in the Frame
Java
// Java Swing Program to Add Checkbox
// in the Frame
import java.awt.*;
// Driver Class
class Lan {
// Main Function
Lan()
{
// Frame Created
Frame f = new Frame();
// CheckBox created
Checkbox c2 = new Checkbox("Hindi");
c2.setBounds(100, 150, 50, 50);
f.add(c2);
// CheckBox created
Checkbox c3 = new Checkbox("English");
c3.setBounds(100, 200, 80, 50);
f.add(c3);
// CheckBox created
Checkbox c4 = new Checkbox("marathi");
c4.setBounds(100, 250, 80, 50);
f.add(c4);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
}
Output:
Output of Example 3
A ImageIcon control is an
Imagelcon implementation of the Icon interface
that paints Icons from Images
void setLayout(LayoutManager
Sets the layout manager for this panel.
layout)
Example of AWT Panel
Below is the implementation of the above topic:
Java
// Driver Class
public class PanelExample {
// main function
public static void main(String[] args) {
panel1.add(button1);
panel1.add(button2);
frame.setSize(400, 200);
frame.setLayout(new FlowLayout());
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});
}
}
Output Screen:
Conclusion
The Panel class in Java AWT is a versatile tool around for
designing well-structured graphic user interfaces. By allowing the
grouping of components within panels, it simplifies and enhances
the GUI plan. This article introduced the Panel class, its methods,
and constructors, and provided an informative model. Armed with
this knowledge, you can in effect purchase the Panel class to
make more unionized and visually pleasing Java applications.
Java Swing – JPanel With Examples
Last Updated : 10 Nov, 2021
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.
Constructors of JPanel
1. JPanel(): creates a new panel with a flow layout
2. JPanel(LayoutManager l): creates a new JPanel with
specified layoutManager
3. JPanel(boolean isDoubleBuffered): creates a new
JPanel with a specified buffering strategy
4. JPanel(LayoutManager l, boolean
isDoubleBuffered): creates a new JPanel with specified
layoutManager and a specified buffering strategy
Commonly used Functions of JPanel
1. add(Component c): Adds a component to a specified
container
2. setLayout(LayoutManager l): sets the layout of the
container to the specified layout manager
3. updateUI(): resets the UI property with a value from the
current look and feel.
4. setUI(PanelUI ui): sets the look and feel of an object
that renders this component.
5. getUI(): returns the look and feel object that renders this
component.
6. paramString(): returns a string representation of this
JPanel.
7. getUIClassID(): returns the name of the Look and feel
class that renders this component.
8. getAccessibleContext(): gets the AccessibleContext
associated with this JPanel.
Let us take a sample program in order to illustrate the use of
JPanel class by appending sequential execution snapshots of
outputs justifying the below program sets as follows:
Example:
Java
// Class 1
// Helper class extending JFrame class
class solution extends JFrame {
// JFrame
static JFrame f;
// JButton
static JButton b, b1, b2;
// Main class
public static void main(String[] args)
{
// Creating a new frame to store text field and
// button
f = new JFrame("panel");
// setbackground of panel
p.setBackground(Color.red);
f.show();
}
}
Output:
Example 2:
Java
// Main class
// Extending JFrame class
class solution extends JFrame {
// JFrame
static JFrame f;
// JButton
static JButton b, b1, b2, b3;
// setbackground of panel
p.setBackground(Color.red);
// Adding panel to frame
f.add(p);
f.show();
}
}
Output:
Example 3:
Java
// Main class
// Extending JFrame class
class solution extends JFrame {
// JFrame
static JFrame f;
// JButton
static JButton b, b1, b2, b3;
f.show();
}
}
Output:
// Driver Class
public class MyJFrame {
// main function
public static void main(String[] args)
{
// Create a new JFrame
JFrame frame = new JFrame("My First JFrame");
// Create a label
JLabel label
= new JLabel("Geeks Premier League 2023");
// Close operation
frame.setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
Output:
// Driver Class
public class JFrameExample {
// Main function
public static void main(String[] args) {
// Create the main frame
JFrame frame = new JFrame("JFrame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 600);
frame.setVisible(true);
}
}
Output:
manage
The Layout managers enable us to control the way in which visual
components are arranged in the GUI forms by determining the size and
position of components within the containers.
Types of LayoutManager
There are 6 layout managers in Java
Example
import java.awt.*;
import javax.swing.*;
public class LayoutManagerTest extends JFrame {
JPanel flowLayoutPanel1, flowLayoutPanel2, gridLayoutPanel1,
gridLayoutPanel2, gridLayoutPanel3;
JButton one, two, three, four, five, six;
JLabel bottom, lbl1, lbl2, lbl3;
public LayoutManagerTest() {
setTitle("LayoutManager Test");
setLayout(new BorderLayout()); // Set BorderLayout for JFrame
flowLayoutPanel1 = new JPanel();
one = new JButton("One");
two = new JButton("Two");
three = new JButton("Three");
flowLayoutPanel1.setLayout(new FlowLayout(FlowLayout.CENTER)); //
Set FlowLayout Manager
flowLayoutPanel1.add(one);
flowLayoutPanel1.add(two);
flowLayoutPanel1.add(three);
flowLayoutPanel2 = new JPanel();
bottom = new JLabel("This is South");
flowLayoutPanel2.setLayout (new FlowLayout(FlowLayout.CENTER)); //
Set FlowLayout Manager
flowLayoutPanel2.add(bottom);
gridLayoutPanel1 = new JPanel();
gridLayoutPanel2 = new JPanel();
gridLayoutPanel3 = new JPanel();
lbl1 = new JLabel("One");
lbl2 = new JLabel("Two");
lbl3 = new JLabel("Three");
four = new JButton("Four");
five = new JButton("Five");
six = new JButton("Six");
gridLayoutPanel2.setLayout(new GridLayout(1, 3, 5, 5)); // Set
GridLayout Manager
gridLayoutPanel2.add(lbl1);
gridLayoutPanel2.add(lbl2);
gridLayoutPanel2.add(lbl3);
gridLayoutPanel3.setLayout(new GridLayout(3, 1, 5, 5)); // Set
GridLayout Manager
gridLayoutPanel3.add(four);
gridLayoutPanel3.add(five);
gridLayoutPanel3.add(six);
gridLayoutPanel1.setLayout(new GridLayout(2, 1)); // Set GridLayout
Manager
gridLayoutPanel1.add(gridLayoutPanel2);
gridLayoutPanel1.add(gridLayoutPanel3);
add(flowLayoutPanel1, BorderLayout.NORTH);
add(flowLayoutPanel2, BorderLayout.SOUTH);
add(gridLayoutPanel1, BorderLayout.CENTER);
setSize(400, 325);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new LayoutManagerTest();
}
}
Learn Java in-depth with real-world projects through our Java certification
course. Enroll and become a certified expert to boost your career.
Output
Java AWT | FlowLayout
Last Updated : 25 Jun, 2018
FlowLayout is used to arrange components in a sequence one
after the other. The default layout of applet and panel is
FlowLayout.
Constructors :
1. FlowLayout(): It will Construct a new FlowLayout with
centered alignment.The horizontal and vertical gap will be
5 pixels.
2. FlowLayout(int align) : It will Construct a new
FlowLayout with given alignment.The horizontal and
vertical gap will be 5 pixels.
3. FlowLayout(int align, int HorizontalGap, int
VerticalGap ): It will Construct a new FlowLayout with
given alignment, the given horizontal and vertical gap
between the components.
4. JLabel(String text): It will create a JLabel instance with
the specified text.
Commonly used methods:
1. setTitle(String Text): This Method is used to set Title of
JFrame. The title you want to set is passed as a string.
2. getAlignment(): Returns the alignment for this layout.
3. setAlignment(int align): used to set the alignment for
this layout.
4. removeLayoutComponent(Component comp): Used
to remove the component passed as argument from the
layout.
Below programs will illustrate the Example of FlowLayout in java.
1. Program 1: The following program illustrates the use of
FlowLayout by arranging several JLabel components in a
JFrame, whose instance class is named as “Example”. We
create 5 JLabel components named “l1”, “l2″… “l5” and
then add them to the JFrame by the method this.add().
We set the title and bounds of the frame by method
setTitle and setBounds.
The layout is set by the method setLayout();
// Java program to show Example of FlowLayout.
// in java. Importing different Package.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MainFrame {
// Driver code
public static void main(String[] args)
{
// Creating Object of Example class.
Example f = new Example();
class MainFrame {
// Driver code
public static void main(String[] args)
{
// Creating Object of Example class.
Example f = new Example();
5. Output:
Java AWT | BorderLayout Class
Last Updated : 06 Oct, 2021
BorderLayout is the default layout for the window objects such as
JFrame, JWindow, JDialog, JInternalFrame etc. BorderLayout
arranges the components in the five regions. Four sides are
referred to as north, south, east, and west. The middle part is
called the center. Each region can contain only one component
and is identified by a corresponding constant
as NORTH, SOUTH, EAST, WEST, and CENTER.
Constructors:
1. BorderLayout(): It will construct a new borderlayout
with no gaps between the components.
2. BorderLayout(int, int): It will constructs a border layout
with the specified gaps between the components.
Commonly Used Methods:
1. toString(): Returns a string which is the representation
of the state of border layout.
2. getLayoutAlignmentX(Container parent): Returns the
layout alignment along the X-axis.
3. getLayoutAlignmentY(Container parent): It will
return the layout alignment along the Y-axis.
4. removeLayoutComponent(Component comp): This
method is used to remove the specified component from
the borderlayout.
5. getVgap(): Return the vertical gap between the
components.
6. getHgap(): Returns the Horizontal gap between the
components.
7. setHgap(int hgap): It is used to set the horizontal gap
between the components.
8. setVgap(int vgap): It is used to set the vertical gap
between the components.
Below Programs will illustrate the BorderLayout class:
Program 1: The following program creates JButton
components in a JFrame, whose instance class is
“BorderLayoutDemo”. We create 5 JButton and then add
them to the JFrame by using add() method. We will set
the size and visibility of the frame by
using setSize() and setVisible() method respectively. The
layout is set by using the setLayout() method.
Java
BoderLayoutDemo()
{
class MainFrame {
// Driver code
public static void main(String[] args)
{
Output:
// Main Method
public static void main(String args[])
{
Output:
Note: The above programs might not run in an online IDE. Please
use an offline compiler.
Java AWT | GridLayout Class
Last Updated : 21 Aug, 2018
GridLayout class represents a layout manager with a specified
number of rows and columns in a rectangular grid. The
GridLayout container is divided into an equal-sized of rectangles,
and one of the components is placed in each rectangle. Every
rectangle cell has the same size therefore, they contain a
component, which fills the entire cell. When the user changes or
adjusts the size of the container, the size of each rectangles
changes accordingly.
Constructors of the class:
1. GridLayout(): It Creates a grid layout with a default of
one column per component, in a single row.
2. GridLayout(int rw, int cl): It creates a grid layout with
the specified number of rows and columns.
3. GridLayout(int rw, int cl, int hgap, int vgap): It
creates a grid layout with the specified number of rows
and columns with horizontal and vertical gap.
Commonly Used Methods:
addLayoutComponent(String str, Component
cmp): Adds the specified component with the specified
name to the layout.
setColumns(int cl): Sets the number of columns in this
layout to the specified value.
setHgap(int hgap): Sets the horizontal gap between
components to the specified value.
setRows(int rw): Sets the number of rows in this layout
to the specified value.
setVgap(int vgap): Sets the vertical gap between
components to the specified value.
layoutContainer(Container pr): Lays out the specified
container using this layout.
toString(): Returns the string representation of this grid
layout’s values.
Below programs illustrate the GridLayout class:
Program 1: In below program we are passing the
argument in GridLayout. We create 4 JLabel components
named “one“, “two“, “three“, “four” and create
2 JButton components named “buttonsave” and
“buttonexit” and create 4 Jtextfield components named
“tname“, “tcode“, “tdesig“, “tsalary” and all of add them
to the JFrame by the method add(). We will set the
visibility and size of the frame by
using setVisible() and setSize() method. The layout is set
by using setLayout() method.
// Java program to illustrate the GridLayout
import javax.swing.*;
import java.awt.*;
GridLayoutDemo() {
// Initialization of object
// "tname" of JTextField class.
tname = new JTextField(20);
// Initialization of object
// "two" of JLabel class.
two = new JLabel("CODE");
// Initialization of object
// "tcode" of JTextField class.
tcode = new JTextField(20);
// Initialization of object
// "three" of JLabel class.
three = new JLabel("DESIGNATION");
// Initialization of object
// "tdesig" of JTextField class.
tdesig = new JTextField(20);
// Initialization of object
// "four" of JLabel class.
four = new JLabel("SALARY");
// Initialization of object
// "tsalary" of JTextField class.
tsalary = new JTextField(20);
// Initialization of object
// "buttonsave" of JButton class.
buttonSave = new JButton("SAVE");
// Initialization of object
// "buttonexit" of JButton class.
buttonExit = new JButton("EXIT");
// Main Method
public static void main(String args[])
{
// calling the constructor
new GridLayoutDemo();
}
}
Output:
Video Player
00:00
00:22
// Main Method
public static void main(String[] args)
{
// Initialization of object
// "btn1" of JButton class.
JButton btn1 = new JButton("Button 1");
// Initialization of object
// "btn2" of JButton class.
JButton btn2 = new JButton("Button 2");
// Initialization of object
// "btn3" of JButton class.
JButton btn3 = new JButton("Button 3");
// Initialization of object
// "btn4" of JButton class.
JButton btn4 = new JButton("Button 4");
// Initialization of object
// "btn5" of JButton class.
JButton btn5 = new JButton("Button 5");
Output:
Video Player
00:00
00:16
Note: The above programs might not run in an online IDE. Please
use an offline compiler.
BoderLayoutDemo()
{
class MainFrame {
// Driver code
public static void main(String[] args)
{
Output:
Program 2: This program will show how to pass the
arguments in BorderLayout. Set the background color by
using setBackground() method. We create 5 JButton
components named “btn1“, “btn2“, “btn3“, “btn4“,
“btn5“, and then add them to the JFrame by
using add() method. We set the title, size, and visibility of
the frame by
using setTitle(), setSize() and setVisible() methods
respectively. The layout is set by the method setLayout().
Java
// Main Method
public static void main(String args[])
{
Output:
Note: The above programs might not run in an online IDE. Please
use an offline compiler.
GUI components
All the important GUI components are listed below
Pointer
Pops up in the screen and proceeds to select objects.
Pointing tool
Picking up of objects is done by pointing tool, for example
– Trackball, Mouse.
Icons
Refers to small images on the screen which represent
commands, documents, and windows.
Desktop
The screen that is contains the icons.
History of GUI
Earlier, there was no GUI so people used to interact with
the command-line interface(CLI). The CLI was not that friendly to
use and the end-user was not familiar with all the commands. So
to bridge this gap, GUI was introduced. The main aim of the GUI
was to make the applications much more user-friendly. People
love when the task which they want to perform gets done easily
and in an efficient manner. GUI stresses one of the most
important aspects which is ease of use. The basic structure of GUI
using implied authority is given in the following diagram
Inherited Methods
The Methods included with AWT button are inherited by:
java.awt.Component
java.lang.Object
Examples of Java AWT Button
Let us understand the AWT Button class and their methods with
some examples given below:
Example 1 (Basic Button):
The example given below is a simple implementation of a Button
with a label.
Java
// Driver Class
public class Main {
// main function
public static void main(String[] args)
{
// Create a frame
Frame frame = new Frame("AWT Button Example");
// Create a button
Button button = new Button("Click Me!");
Output:
// Driver Class
public class Main {
// main function
public static void main(String[] args){
// Create a frame
Frame frame = new Frame("AWT Button Example");
// Button 1
Button button1 = new Button("Click Me!");
Output:
// Driver Class
public class Main {
// main function
public static void main(String[] args)
{
// Create a frame
Frame frame = new Frame("AWT Button Example");
// Create a button
Button b = new Button("Click Here!");
// Create a label
Label label = new Label();
// Set the position of the label
label.setBounds(80, 140, 280, 20);
Output:
Final Output Created: