SlideShare uma empresa Scribd logo
1 de 21
Responding to User
Swing handles events with a set of interfaces
called event listeners. You create a listener
object and associate it with the user interface
component being monitored.
Event Listeners
If a class wants to respond to a user event under the
Java event-handling system, it must implement the
interface that deals with the events. These interfaces
are called event listeners.
• Each listener handles a specific kind of event.
The java.awt.event package contains all the basic
event listeners, as well as the objects that represent
specific events.
• ActionListener—Action events, which are generated
by a user taking an action on a component, such as a
click on a button
• AdjustmentListener—Adjustment events, which are
generated when a component is adjusted, such as
when a scrollbar is moved
• FocusListener—Keyboard focus events, which are
generated when a component such as a text field
gains or loses the focus
• KeyListener—Keyboard events, which occur when a
user enters text on the keyboard
• MouseListener—Mouse events, which are generated
by mouse clicks, a mouse entering a component’s
area, and a mouse leaving a component’s area
• WindowListener—Window events, which are
generated by a window being maximized, minimized,
moved, or closed
A class can implement as many listeners as needed. The
following class is declared to handle both action and text
events:
public class Test extends JFrame implements ActionListener
{
// ...
}
Setting Up Components
When you make a class an event listener, you have set up
a specific type of event to be heard by that class.
The following example creates a JButton object and
associates an action event listener with it:
JButton ok = new JButton(“OK”);
ok.addActionListener(this);
All the listener adding methods take one
argument: the object that is listening for events
of that kind. Using “this” indicates that the
current class is the event listener. You could
specify a different object, as long as its class
implements the right listener interface.
Event-Handling Methods
When you associate an interface with a class, the class
must handle all the methods contained in the interface.
The ActionListener interface has only one method:
actionPerformed(). All classes that implement
ActionListener must have a method with the following
structure:
public void actionPerformed(ActionEvent event)
{
// handle event here
}
If only one component in your program’s graphical
user interface has a listener for action events, you will
know that this actionPerformed() method only is
called in response to an event generated by that
component.
If more than one component has an action event
listener, you must use the ActionEvent object to
figure out which component was used and act
accordingly in your program. This object can be used
to discover details about the component that
generated the event.
public void actionPerformed(ActionEvent event)
{
Object source = evt.getSource();
}
The object returned by the getSource() method can
be compared with components by using the ==
operator.
if (source == quitButton) {
quitProgram();
}
if (source == sortRecords) {
sortRecords();
}
The quitProgram() method is called if the
quitButton object generated the event, and the
sortRecords() method is called if the sortRecords
button generated the event.
The instanceof operator can be used in an event-
handling method to determine what class of
component generated the event.
void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source instanceof JTextField) {
calculateScore();
} else if (source instanceof JButton) {
quitProgram();
}
}
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class TitleChanger extends JFrame implements ActionListener
{
JButton b1 = new JButton("ATI NAIWALA");
JButton b2 = new JButton("ATI DEHIWALA");
public TitleChanger() {
super("Title Bar");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
b1.addActionListener(this);
b2.addActionListener(this);
FlowLayout flow = new FlowLayout();
setLayout(flow);
add(b1);
add(b2);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();
if (source == b1) {
setTitle("ATI NAIWALA");
} else if (source == b2) {
setTitle("ATI DEHIWALA");
}
repaint();
}
public static void main(String[] arguments) {
TitleChanger frame = new TitleChanger();
}
}
In addition to the getSource() method, you can use the
getActionCommand() method on the ActionEvent object
to discover more information about the event’s source.
By default, the action command is the text associated
with the component, such as the label on a button. You
also can set a different action command for a
component by calling its setActionCommand(String)
method. The string argument should be the action
command’s desired text.
JButton sort = new JButton(“Sort”);
JMenuItem menuSort = new JMenuItem(“Sort”);
sort.setActionCommand(“Sort Files”);
menuSort.setActionCommand(“Sort Files”);
Action commands are useful in a program in which
more than one component should cause the same
thing to happen. By giving both components the
same action command, you can handle them with
the same code in an event-handling method.
Focus Events
Focus events occur when any component gains or
loses input focus on a graphical user interface.
Focus describes the component that is active for
keyboard input. If one of the fields has the focus (in a
user interface with several editable text fields), a
cursor blinks in the field. Any text entered goes into
this component.
A component can be given the focus by calling its
requestFocus() method with no arguments,
JButton ok = new JButton(“OK”);
ok.requestFocus();
To handle a focus event, a class must implement the
FocusListener interface. Two methods are in the
interface: focusGained(FocusEvent) and
focusLost(FocusEvent).
They take the following forms:
public void focusGained(FocusEvent event) {
// ...
}
public void focusLost(FocusEvent event) {
// ...
}
mport java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class Calculator extends JFrame implements
FocusListener {
JTextField value1 = new JTextField("0", 5);
JLabel plus = new JLabel("+");
JTextField value2 = new JTextField("0", 5);
JLabel equals = new JLabel("=");
JTextField sum = new JTextField("0", 5);
public Calculator() {
super("Add Two Numbers");
setSize(350, 90);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flow = new
FlowLayout(FlowLayout.CENTER);
setLayout(flow);
// add listeners
value1.addFocusListener(this);
value2.addFocusListener(this);
sum.setEditable(false);
add(value1);
add(plus);
add(value2);
add(equals);
add(sum);
setVisible(true);
}
public void focusGained(FocusEvent event) {
try {
float total = Float.parseFloat(value1.getText()) +
Float.parseFloat(value2.getText());
sum.setText("" + total);
} catch (NumberFormatException nfe) {
value1.setText("0");
value2.setText("0");
sum.setText("0");
}
}
public void focusLost(FocusEvent event) {
focusGained(event);
}
public static void main(String[] arguments) {
Calculator frame = new Calculator();
}
}
event handling new.ppt

Mais conteúdo relacionado

Semelhante a event handling new.ppt

Semelhante a event handling new.ppt (20)

Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024Java Abstract Window Toolkit (AWT) Presentation. 2024
Java Abstract Window Toolkit (AWT) Presentation. 2024
 
Synapseindia dotnet development chapter 14 event-driven programming
Synapseindia dotnet development  chapter 14 event-driven programmingSynapseindia dotnet development  chapter 14 event-driven programming
Synapseindia dotnet development chapter 14 event-driven programming
 
engineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.pptengineeringdsgtnotesofunitfivesnists.ppt
engineeringdsgtnotesofunitfivesnists.ppt
 
What is Event
What is EventWhat is Event
What is Event
 
Ajp notes-chapter-03
Ajp notes-chapter-03Ajp notes-chapter-03
Ajp notes-chapter-03
 
Advance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handlingAdvance Java Programming(CM5I) Event handling
Advance Java Programming(CM5I) Event handling
 
Unit 6 Java
Unit 6 JavaUnit 6 Java
Unit 6 Java
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Androd Listeners
Androd ListenersAndrod Listeners
Androd Listeners
 
Lecture8 oopj
Lecture8 oopjLecture8 oopj
Lecture8 oopj
 
OOP Lecture 11-EventHandling1.pptx
OOP Lecture 11-EventHandling1.pptxOOP Lecture 11-EventHandling1.pptx
OOP Lecture 11-EventHandling1.pptx
 
event-handling.pptx
event-handling.pptxevent-handling.pptx
event-handling.pptx
 
Jp notes
Jp notesJp notes
Jp notes
 
Event handling
Event handlingEvent handling
Event handling
 
File Handling
File HandlingFile Handling
File Handling
 
ACtionlistener in java use in discussion.pptx
ACtionlistener in java use in discussion.pptxACtionlistener in java use in discussion.pptx
ACtionlistener in java use in discussion.pptx
 
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 Dr Jammi Ashok - Introduction to Java Material (OOPs) Dr Jammi Ashok - Introduction to Java Material (OOPs)
Dr Jammi Ashok - Introduction to Java Material (OOPs)
 
JAVA AWT
JAVA AWTJAVA AWT
JAVA AWT
 
Swing
SwingSwing
Swing
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

event handling new.ppt

  • 2. Swing handles events with a set of interfaces called event listeners. You create a listener object and associate it with the user interface component being monitored. Event Listeners If a class wants to respond to a user event under the Java event-handling system, it must implement the interface that deals with the events. These interfaces are called event listeners. • Each listener handles a specific kind of event.
  • 3. The java.awt.event package contains all the basic event listeners, as well as the objects that represent specific events. • ActionListener—Action events, which are generated by a user taking an action on a component, such as a click on a button • AdjustmentListener—Adjustment events, which are generated when a component is adjusted, such as when a scrollbar is moved • FocusListener—Keyboard focus events, which are generated when a component such as a text field gains or loses the focus
  • 4. • KeyListener—Keyboard events, which occur when a user enters text on the keyboard • MouseListener—Mouse events, which are generated by mouse clicks, a mouse entering a component’s area, and a mouse leaving a component’s area • WindowListener—Window events, which are generated by a window being maximized, minimized, moved, or closed
  • 5. A class can implement as many listeners as needed. The following class is declared to handle both action and text events: public class Test extends JFrame implements ActionListener { // ... } Setting Up Components When you make a class an event listener, you have set up a specific type of event to be heard by that class.
  • 6. The following example creates a JButton object and associates an action event listener with it: JButton ok = new JButton(“OK”); ok.addActionListener(this); All the listener adding methods take one argument: the object that is listening for events of that kind. Using “this” indicates that the current class is the event listener. You could specify a different object, as long as its class implements the right listener interface.
  • 7. Event-Handling Methods When you associate an interface with a class, the class must handle all the methods contained in the interface. The ActionListener interface has only one method: actionPerformed(). All classes that implement ActionListener must have a method with the following structure: public void actionPerformed(ActionEvent event) { // handle event here }
  • 8. If only one component in your program’s graphical user interface has a listener for action events, you will know that this actionPerformed() method only is called in response to an event generated by that component. If more than one component has an action event listener, you must use the ActionEvent object to figure out which component was used and act accordingly in your program. This object can be used to discover details about the component that generated the event.
  • 9. public void actionPerformed(ActionEvent event) { Object source = evt.getSource(); } The object returned by the getSource() method can be compared with components by using the == operator.
  • 10. if (source == quitButton) { quitProgram(); } if (source == sortRecords) { sortRecords(); } The quitProgram() method is called if the quitButton object generated the event, and the sortRecords() method is called if the sortRecords button generated the event.
  • 11. The instanceof operator can be used in an event- handling method to determine what class of component generated the event. void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source instanceof JTextField) { calculateScore(); } else if (source instanceof JButton) { quitProgram(); } }
  • 12. import java.awt.event.*; import javax.swing.*; import java.awt.*; public class TitleChanger extends JFrame implements ActionListener { JButton b1 = new JButton("ATI NAIWALA"); JButton b2 = new JButton("ATI DEHIWALA"); public TitleChanger() { super("Title Bar"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); b1.addActionListener(this); b2.addActionListener(this); FlowLayout flow = new FlowLayout(); setLayout(flow); add(b1); add(b2); pack(); setVisible(true); }
  • 13. public void actionPerformed(ActionEvent evt) { Object source = evt.getSource(); if (source == b1) { setTitle("ATI NAIWALA"); } else if (source == b2) { setTitle("ATI DEHIWALA"); } repaint(); } public static void main(String[] arguments) { TitleChanger frame = new TitleChanger(); } }
  • 14. In addition to the getSource() method, you can use the getActionCommand() method on the ActionEvent object to discover more information about the event’s source. By default, the action command is the text associated with the component, such as the label on a button. You also can set a different action command for a component by calling its setActionCommand(String) method. The string argument should be the action command’s desired text.
  • 15. JButton sort = new JButton(“Sort”); JMenuItem menuSort = new JMenuItem(“Sort”); sort.setActionCommand(“Sort Files”); menuSort.setActionCommand(“Sort Files”); Action commands are useful in a program in which more than one component should cause the same thing to happen. By giving both components the same action command, you can handle them with the same code in an event-handling method.
  • 16. Focus Events Focus events occur when any component gains or loses input focus on a graphical user interface. Focus describes the component that is active for keyboard input. If one of the fields has the focus (in a user interface with several editable text fields), a cursor blinks in the field. Any text entered goes into this component. A component can be given the focus by calling its requestFocus() method with no arguments, JButton ok = new JButton(“OK”); ok.requestFocus();
  • 17. To handle a focus event, a class must implement the FocusListener interface. Two methods are in the interface: focusGained(FocusEvent) and focusLost(FocusEvent). They take the following forms: public void focusGained(FocusEvent event) { // ... } public void focusLost(FocusEvent event) { // ... }
  • 18. mport java.awt.event.*; import javax.swing.*; import java.awt.*; public class Calculator extends JFrame implements FocusListener { JTextField value1 = new JTextField("0", 5); JLabel plus = new JLabel("+"); JTextField value2 = new JTextField("0", 5); JLabel equals = new JLabel("="); JTextField sum = new JTextField("0", 5);
  • 19. public Calculator() { super("Add Two Numbers"); setSize(350, 90); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); FlowLayout flow = new FlowLayout(FlowLayout.CENTER); setLayout(flow); // add listeners value1.addFocusListener(this); value2.addFocusListener(this); sum.setEditable(false); add(value1); add(plus); add(value2); add(equals); add(sum); setVisible(true); }
  • 20. public void focusGained(FocusEvent event) { try { float total = Float.parseFloat(value1.getText()) + Float.parseFloat(value2.getText()); sum.setText("" + total); } catch (NumberFormatException nfe) { value1.setText("0"); value2.setText("0"); sum.setText("0"); } } public void focusLost(FocusEvent event) { focusGained(event); } public static void main(String[] arguments) { Calculator frame = new Calculator(); } }